Using Ultrasonic Distance Sensor Module HC-SR04 with an Arduino


I just got hold of an HC-SR04 Ultrasonic Sensor Module. This is a short post on hooking it up to an Arduino Uno and getting distance information from it.


The sensor has 4 pins – VCC (5V), GND, Trigger and Echo. Looking at the datasheet for HC-SR04, the way it work is:


  • Send a 10us HIGH pulse on the Trigger pin.
  • The sensor sends out a “sonic burst” of 8 cycles.
  • Listen to the Echo pin, and the duration of the next HIGH signal will give you the time taken by the sound to go back and forth from sensor to target.

This is what it looks like hooked to the Arduino:


 


And here is the Arduino code:


 

// HC-SR04-test.ino
//
// Get distance information from Ultrasonic Ranging Module HC-SR04 and
// send it via serial port.
//
// electronut.in

#include "Arduino.h"

int pinTrigger = 2;
int pinEcho = 4;

void setup()
{
// initialize serial comms
Serial.begin(9600);

// set pins
pinMode(pinTrigger, OUTPUT);
pinMode(pinEcho, INPUT);
}

void loop()
{
// send a 10us+ pulse
digitalWrite(pinTrigger, LOW);
delayMicroseconds(20);
digitalWrite(pinTrigger, HIGH);
delayMicroseconds(10);
digitalWrite(pinTrigger, LOW);
delayMicroseconds(20);

// read duration of echo
int duration = pulseIn(pinEcho, HIGH);

if(duration > 0) {
// dist = duration * speed of sound * 1/2
// dist in cm = duration in us * 1 x 10^{-6} * 340.26 * 100 * 1/2
// = 0.017*duration
float dist = 0.017 * duration;
Serial.println(dist);
}

// wait
delay(70);
}

This is what the distance plot looks like as I walk to towards the sensor. This is done using Python and matplotlib – please take a look at my post on plotting real-time data with Python.


 


The datasheet says that the sensor has a range of 2cm to 400 cm, and an accuracy of 3mm. The target needs to be 0.5 sq m, so it’s not going to be very useful to scan for small objects. But it could be useful in many other situations. The sensor is cheap – about Rs. 250, and I could get it from ebay.in easily.