ultrason-hcsr04.ino
The HC-SR04 ultrasonic sensor measures distance by time of flight: the 10 µs TRIG pulse fires a 40 kHz burst, pulseIn times the echo, and dividing by 58 converts microseconds into centimetres. A hands-on Arduino Nano classic.
Hardware
An Arduino Nano classic (ATmega328P at 16 MHz, 30-pin DIL breadboard footprint, mini-B USB, 5 V logic, RESET pin at the lower-left corner). Arduino Nano, HC-SR04 (VCC 5 V, TRIG, ECHO, GND). ECHO outputs 5 V: fine on the 328P 5 V-tolerant inputs.
Wiring
TRIG→D12, ECHO→D13, VCC→5 V, GND→GND. Do not power at 3.3 V: the module is designed for 5 V.
How it works
pulseIn(ECHO, HIGH, 30000) times the pulse with a timeout preventing a hang when nothing returns. Sound speed (340 m/s) over the round trip gives the 58 µs/cm factor.
Running it
In the Arduino IDE, select the Arduino Nano board and ATmega328P processor, pick the serial port, then upload. The board's 5 V rail suits 5 V sensors; otherwise use 3.3 V on compatible pins.
Variants
Average 5 readings to stabilise the display, or drive a servo for a 180° radar (the base of Processing "radar" projects).
ultrason-hcsr04.ino
// Distance cm avec HC-SR04 sur l'Arduino Nano (broches 12/13).
const int TRIG = 12;
const int ECHO = 13;
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
Serial.begin(9600);
}
void loop() {
// L'impulsion de declenchement doit durer 10 microsecondes
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// pulseIn attend l'aller-retour de l'echo (timeout 30 ms = 5 m)
long duree = pulseIn(ECHO, HIGH, 30000);
if (duree == 0) {
Serial.println(F("hors portee"));
} else {
// 340 m/s / 2 (aller-retour) = 58 us par cm
float distance = duree / 58.0;
Serial.print("distance : ");
Serial.print(distance, 1);
Serial.println(" cm");
}
delay(100); // laisser retomber l'echo precedent
}