Sulabh Sethi · Blog ← Main Site

Ultrasonic Sensors and the HC-SR04

How ultrasonic sensors measure distance with sound, the parts of the common HC-SR04 module, and an Arduino example that classifies an object as Near, Far, or Too Far.

Embedded Systems · 9 August 2023 · 2 min read

HC-SR04 ultrasonic sensor

Ultrasonic sensors use sound waves to measure distance and detect objects. They emit short bursts of high-frequency sound (typically above 20,000 Hz, beyond human hearing) that travel through the air and bounce back when they hit an object. Think of them as the ears of a machine: from the returning sound, the sensor can tell how close or far an object is, for informed decision making.

When the waves hit an obstacle, they reflect back and are read by a receiver in the sensor. By measuring the time the waves take to travel to the object and back, the sensor calculates the distance. This is analogous to how human hearing locates objects by the timing and intensity of sound. Common applications include obstacle detection and avoidance, distance-based decisions in smart factories, robotics, automation, pick-and-place machines, parking sensors, and distance sensing.

Advantages

Easy to interface, available in waterproof versions, versatile, zero physical contact, and based on the simple law of reflection.

HC-SR04 components

The most commonly used ultrasonic sensor for non-military-grade applications is the HC-SR04.

  1. Transmitter: emits high-frequency sound waves of around 40 kHz.
  2. Receiver: detects the ultrasonic waves reflected back from objects.
  3. Protruding sensors: the two circular elements on the front, one transmitter and one receiver.
  4. VCC: power to the module, typically 5V.
  5. GND: ground.
  6. Trig: triggers the ultrasonic pulse, connected to a digital output pin.
  7. Echo: receives the reflected signal, connected to a digital input pin.

Example code

This code classifies an object as Near (within 5cm), Far (within 10cm), or Too Far (beyond 10cm).

const int trigger = 2; // Trig pin connected to digital pin 2
const int echo = 3; // Echo pin connected to digital pin 3
const int neard = 5; // Near threshold (cm)
const int fard = 10; // Far threshold (cm)
const float speedOfSound = 0.0343;
long duration;
int distance;
void setup() {
Serial.begin(9600);
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
}
void loop() {
// Send a 10us high pulse to trigger the sensor
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
// Measure the echo pulse and convert to distance
duration = pulseIn(echo, HIGH);
distance = duration * speedOfSound / 2;
Serial.print("Distance from sensor: ");
Serial.print(distance);
Serial.println(" cm");
if (distance <= neard) {
Serial.println("Near");
} else if (distance <= fard) {
Serial.println("Far");
} else {
Serial.println("Too Far Away");
}
delay(1000);
}

Originally published on sslabs.in.