Arduino Ultrasonic Sensor HC-SR04

This post is about building a distance meter using HC-SR04 Ultrasonic Sensor and Arduino MEGA board. For PIC16F877 version click here. HC-SR04 module can measure distances ranging from 2cm – 400 cm. The interface is relatively simple. According to sensor datasheet a short 10us pulse should be provided to Trigger pin of HC-SR04 to initiate sending eight 40 kHz pulses to the target. Then you need to measure the time it takes for Echo pin go High in milliseconds and convert it to distance according to this formula: uS / 58 = centimeters or uS / 148 = inch. Schematic diagram is shown in the next figure.
Arduino Ultrasonic Sensor HC-SR04 Schematic
In my previous post I’ve used my own functions to interface with LCD display. These functions were essentially a modified code taken from PIC assembly language and used 8 bit parallel interface wasting a lot of I/O, however for this design I’ve decided to embrace Arduino LCD library LiquidCrystal.h and use its functions. So now only 6 I/O are needed. 4 for LCD Data – D7..D4 and 2 for RS and EN pin, leaving pin 6,7 for Trig and Echo signal. This implementation should also work on Arduino UNO and all compatible boards. Arduino distance meter code can be downloaded at this link.

I’ve added a small piece of code to the sketch to show “Range” on the LCD in the upper left corner if the distance to the object is less than 2 cm or greater than 400 cm, otherwise it does not provide a correct reading. And finally here is short video showing the distance meter in action.


Leave a Reply

Your email address will not be published. Required fields are marked *