Chapter 9 · Arduino Practicals and Programming Projects

Practical 4Connecting an Ultrasonic Sensor with Arduino UNO R3

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-SR04Arduino
VCC5V
TrigPin 9
EchoPin 10
GNDGND
Arduino UNO5VPin 9Pin 10GNDHC-SR04VCCTrigEchoGNDTrig → pin 9Echo → pin 10
Practical 4 circuit

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.

  1. Upload and open the Serial Monitor at 9600 baud.
  2. 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.
  3. 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

  1. Why do we divide by 2?
  2. What is the frequency of the ultrasound?
  3. What reading would you expect from a distance of 1 m?
  4. Why might a reading be wrong for a sponge?
Show viva answers
  1. The measured time covers the trip to the object and back.
  2. About 40 kHz.
  3. Round trip of 200 cm: time = 200 / 0.0343 ≈ 5831 µs.
  4. Soft materials absorb the sound instead of reflecting it.