25 August, 2014

Calculating distance with the HC-SR04

By Mauricio Hidalgo

A few days ago we published an article talking about Module HC SR04, and how important is to  robotics and Arduino projects, so today I bring a test of this module, which will test a small code to measure the distance at which it is an obstacle. Recall that the measurement range of this module is from 2cm to 400cm, so we will put to test  an obstacle to 20cm in front of the ultrasonic sensor and this is enough for now to test the module and verify it’s accurate detection.

Picture 78

Calculating distance with Arduino shield HC SR04

To perform this little test we require the following materials:

1.  Arduino Mega 2560

2.  HC-SR04 Ultrasonic Sensor

3.  meter or ruler to determine distances

4 Protoboard

5 connection cables

For this test also connect the sensor to 5V Arduino Mega and implement the following code:

HCSR04 code

 

If you do not like to type what appears on the image, you can find the code in my GitHub repository on  following LINK.

In this code we see the implementation of key instructions, as in the case of attachInterrupt () instruction, that allows you to enable interrupts on the Arduino Mega board and micros () instruction, also allows to take the exact time in micro seconds of the moment that wish,  additionally we use the formula provides by the manufacturer of HC-SR04 sensor that is:

range = high level time * velocity (344M/S) / 2

This statement and the additional information of the sensor located at the following LINK, is a pdf with the technical characteristics of the  HC-SR04 sensor.

Finally I leave a video in which I explain in detail the implementation of this code and testing calculation distance an obstacle is performed.

There is another code to perform this test, which are in the following LINK and where implement a library developed for this sensor arduino-new-ping is called.

To test these codes and make good use of them in their future projects.