Microcontroller Tutorials

Arduino, Raspberry Pi, PIC, Beaglebone Resources

HC-SR04 and Arduino Interfacing Tutorial

An ultrasonic sensor like the HC-SR04 finds a lot of applications because of its low cost and ease of use.

Introduction

Ultrasonic literally means "sound beyond what humans hear" which is the signal emitted by the module. By measuring when the signal is emitted and when it is sent back to the receiver, we can measure the distance between the ultrasonic sensor and the body that reflected the signal. In this tutorial, we will use the HC-SR04 with an Arduino to measure the distance from an obstacle.

The HC-SR04 Module

The HC-SR04 module has four pins (Vcc, Trigger, Echo, Gnd) as shown:

ultrasonic sensor arduino

When the trigger pin is held high, the module begins emitting ultrasonic signal until the pin is pulled low. If the signal encounters an obstacle, it will return back to the module. As a result, the "echo" of the signal is used to measure the distance: the duration between the sending of the signal and the return of the signal can be read on the echo pin as a pulse.

The distance in centimeters between the HC-SR04 and the obstacle can then be calculated using

where 0.034 is derived from the speed of sound: 340 m/s

Arduino Sketch

Here is an Arduino sketch that measures the distance of an obstacle and prints it on the serial monitor:

This ultrasonic sensor module can also be used to measure the presence of an obstacle in front of the module. See my hexapod walker robot project where I used the HC-SR04 to detect an obstacle in front of a robot.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.