Le HC-SR04 est un capteur de distance à ultrasons qui mesure la portée en envoyant une impulsion sonore et en chronométrant le retour de l’écho. Il utilise généralement une alimentation de 5V et une interface numérique simple trigger/echo, ce qui le rend facile à lire dans des projets basés sur Arduino et ESP32.
| Broche | Signal | Description |
|---|---|---|
Vcc |
power | bottom-edge power pin hole, leftmost of the 4-pin header |
Trig |
digital | bottom-edge trigger pin hole, second from left |
Echo |
digital | bottom-edge echo pin hole, third from left |
Gnd |
ground | bottom-edge ground pin hole, rightmost of the 4-pin header |
| De | Vers | Fil |
|---|---|---|
board:5V |
x1:Vcc |
red |
board:GND |
x1:Gnd |
black |
board:D9 |
x1:Trig |
green |
board:D10 |
x1:Echo |
blue |
Cet exemple a été écrit et vérifié à la compilation pour le arduino-uno. Codey Online l'adapte pour vous à toute autre carte prise en charge.
// HC-SR04 ultrasonic distance sensor example
// Wiring:
// HC-SR04 Vcc -> 5V
// HC-SR04 Gnd -> GND
// HC-SR04 Trig -> D9
// HC-SR04 Echo -> D10
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(trigPin, LOW);
Serial.println("HC-SR04 ready");
}
void loop() {
// Send a 10 microsecond pulse to start a measurement
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse length (timeout after 30 ms)
unsigned long duration = pulseIn(echoPin, HIGH, 30000UL);
if (duration == 0) {
Serial.println("Out of range or no echo");
} else {
// Convert time to distance in centimeters
// Speed of sound approx. 343 m/s => 29.1 us per cm round trip
float distanceCm = duration / 58.0;
Serial.print("Distance: ");
Serial.print(distanceCm, 1);
Serial.println(" cm");
}
delay(500);
}
Décrivez ce que vous voulez créer. Codey Online écrit le code, dessine le schéma de câblage, le compile et flashe votre carte directement depuis le navigateur.
Commencez gratuitement