Using a HY-SR05 sensor to measure distance with Arduino

Using a basic Arduino Uno micro-controller board and a HY-SR05 sensor, you can measure distance easily and just about anywhere.

The sensor used here is an HY-SRF05 but for most applications, I would recommend an HC-SR04. Both are ultrasonic sensors that ping a sound wave with a transmitter and measure the distance that ping took to return to the receiver. The only difference between the two is the SRF05 sensor has an extra pin labeled “OUT” which could be used to connect the sensor to an oscilloscope and view the pings that are being triggered. For most practical purposes, this pin will not be needed.

If not done so already, download the Arduino software in the following link . Being a first time Arduino user myself and searching around the web, the best resource is to go through the Arduino provided tutorials The programming language for Arduino is a set of C/C++ functions that can be called from the code.

Next connect the sensor to the Arduino with four female-to-male jumper wires. Connect the pins on the sensor to the Arduino in the following configuration.

Below is the source code to activate the sensor and have it output the distance as the output.

// print distance to serial — hy_sr05
// Ty Seyoum

#define ECHOPIN 2 // Pin to receive echo pulse
#define TRIGPIN 3 // Pin to send trigger pulse

void setup(){
 Serial.begin(9600); //

void loop(){
 digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
 digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
 digitalWrite(TRIGPIN, LOW); // Send pin low again
 int distance = pulseIn(ECHOPIN, HIGH); // Read in times pulse
 distance= distance/58; // Calculate distance from time of pulse
 delay(200); // Wait 50mS before next ranging

Once you compile or “verify” the code above, go ahead and run the program by clicking on the “upload” button. To open the console on Arduino, go to the Tools tab and select “Port: COM4”. Once initiated, the output (in centimeters) will be shown.

The sensor is sitting on my desk pointing at the ceiling. I place a textbook over it for a few seconds and then move the textbook away. That’s what the console is showing.

Have fun!