Aim. To measure distance with an HC-SR04 and display it on the Serial Monitor.
Components. Arduino UNO R3, HC-SR04, jumper wires, ruler or tape measure.
Concepts used. Digital output pulse, pulseIn(), speed of sound, serial output.
Wiring.
| HC-SR04 | Arduino |
|---|---|
| VCC | 5V |
| Trig | Pin 9 |
| Echo | Pin 10 |
| GND | GND |
Program.
Arduino C/C++
const int trigPin = 9;
const int echoPin = 10;
long duration;
float distanceCm;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// send a clean 10 microsecond pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH, 30000); // timeout 30 ms (about 5 m)
if (duration == 0) {
Serial.println("Out of range");
} else {
distanceCm = duration * 0.0343 / 2.0;
Serial.print("Distance: ");
Serial.print(distanceCm, 1); // one decimal place
Serial.println(" cm");
}
delay(300);
}The third argument of pulseIn() is a timeout, which prevents the program from waiting forever when no echo returns.
Procedure.
- Upload and open the Serial Monitor at 9600 baud.
- Place a flat board (such as a book) in front of the sensor at 10 cm, 20 cm, 30 cm and 50 cm, measuring with a ruler.
- Record the Serial Monitor readings in a table and calculate the error.
| Actual (cm) | Measured (cm) | Error (cm) |
|---|---|---|
| 10 | ||
| 20 | ||
| 30 | ||
| 50 |
Expected result. Readings within about 1 cm of the ruler for flat, hard targets in the 5 to 100 cm range.
Improvement: averaging. Take five readings and average them to reduce noise.
Arduino C/C++
float readDistance() {
long total = 0;
int valid = 0;
for (int i = 0; i < 5; i++) {
digitalWrite(trigPin, LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH); delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long d = pulseIn(echoPin, HIGH, 30000);
if (d > 0) { total += d; valid++; }
delay(10);
}
if (valid == 0) return -1; // no valid echo
return (total / (float)valid) * 0.0343 / 2.0;
}Viva questions
- Why do we divide by 2?
- What is the frequency of the ultrasound?
- What reading would you expect from a distance of 1 m?
- Why might a reading be wrong for a sponge?
Show viva answers
- The measured time covers the trip to the object and back.
- About 40 kHz.
- Round trip of 200 cm: time = 200 / 0.0343 ≈ 5831 µs.
- Soft materials absorb the sound instead of reflecting it.