All code examples

Ultrasonic distance โ€” Arduino code

The HC-SR04 sends a burst of sound and times the echo coming back. Divide that time by 58 and you get the distance in centimetres.

What you need

  • โ€ข Arduino Uno
  • โ€ข 1 ร— HC-SR04 ultrasonic sensor
  • โ€ข 4 jumper wires

Wiring

  1. 1VCC to 5 V
  2. 2GND to GND
  3. 3TRIG to digital pin 9
  4. 4ECHO to digital pin 10

The code

ultrasonic-distance.ino
const int TRIG = 9;
const int ECHO = 10;

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
}

void loop() {
  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  long duration = pulseIn(ECHO, HIGH);
  long cm = duration / 58;

  Serial.print("Distance: ");
  Serial.print(cm);
  Serial.println(" cm");
  delay(200);
}

Line by line

Serial.begin(9600);
Opens the link to the Serial Monitor so you can see the readings.
digitalWrite(TRIG, HIGH); delayMicroseconds(10);
A 10 microsecond pulse tells the sensor to ping.
pulseIn(ECHO, HIGH);
Measures how long the echo pin stays high, in microseconds.
duration / 58
Sound travels 1 cm out and back in roughly 58 ยตs, so this converts to centimetres.

When it does not work

It always prints 0
Check TRIG and ECHO are not swapped, and that the sensor has a solid 5 V โ€” it will not fire on 3.3 V.
Readings jump around
Soft surfaces and angled objects scatter the sound. Take three readings and use the middle one, and keep the sensor pointing straight at the target.
What range does it have?
About 2 cm to 400 cm. Anything closer than 2 cm reads as noise.

Want the theory behind it?

More code examples