electronut Programming & Embedded Systems - by Mahesh Venkitachalam

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:

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.

If you liked this article, please consider supporting my efforts by purchasing my book.

Python Playground, published by No Starch Press, USA, is a collection of imaginative programming projects that will inspire you to use Python to make art and music, build simulations of real-world phenomena, and interact with hardware like the Arduino and Raspberry Pi. Do check it out!