DIY ELECTRONICSTR

← All projects

HC-SR04 Ultrasonic Distance Meter

Beginner20 min

A project that measures the distance to the object in front of an HC-SR04 ultrasonic sensor in centimetres and writes it to the Serial Monitor about 10 times a second. The sensor measures how long the echo of its sound wave takes to come back; the code turns that time into centimetres by dividing it by 58. No extra library needed.

Build it step by step in the app

What you need

Wiring steps

  1. 1

    Power the sensor

    Power the sensor

    Plug a red jumper wire into the 5V pin on the Arduino's POWER header. Connect its other end to the HC-SR04's Vcc pin.

  2. 2

    Connect the trigger (Trig) line

    Connect the trigger (Trig) line

    Plug a green jumper wire into the Arduino's digital pin 2. Connect its other end to the HC-SR04's Trig pin. The Arduino starts a measurement by sending a 10-microsecond pulse on this pin (HC_TRIG 2).

  3. 3

    Connect the echo (Echo) line

    Connect the echo (Echo) line

    Plug a blue jumper wire into the Arduino's digital pin 3. Connect its other end to the HC-SR04's Echo pin. The sensor holds this pin HIGH until the sound wave has gone and come back; the code measures that time with pulseIn (HC_ECHO 3).

  4. 4

    Ground (GND) connection

    Ground (GND) connection

    Plug a black jumper wire into the GND pin on the Arduino's POWER header. Connect its other end to the HC-SR04's Gnd pin. That completes all four of the sensor's connections.

Arduino sketch

#define HC_TRIG 2   
#define HC_ECHO 3   

unsigned long duration; 
uint16_t distance;    

void setup() {
  Serial.begin(9600);             
  pinMode(HC_TRIG, OUTPUT);        
  pinMode(HC_ECHO, INPUT);         
  digitalWrite(HC_TRIG, LOW);      
}

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

  // Timeout set to 30,000 uS (approx. 5 meters)
  duration = pulseIn(HC_ECHO, HIGH, 30000);   
  
  if (duration == 0) {
    Serial.println("Distance: Out of Range!");
  } else {
    distance = duration / 58;           
    Serial.print("Distance = ");       
    Serial.print(distance);
    Serial.println(" cm");
  }
  
  delay(100);
}

What the Serial Monitor shows

SERIAL MONITOR · 9600 BAUD
Distance = 12 cm
Distance = 13 cm

If a wire is loose

SERIAL MONITOR · 9600 BAUD
Distance: Out of Range!

In the app, tick off every wire, match the parts to your inventory and pick up where you left off.

Build it step by step in the app