Using a HC-SR04 distance sensor
What is the HC-SR04?
The HC-SR04 is a ultrasonic distance sensor, it uses ultrasound to send out a ping and measure how long the sound takes to come back, exactly like bats use to fly in the dark.
The sensor works between 2-400cm however if the ping sound is reflected away from the sensor by an a divergent (not parallel) surface, or absorbed by a soft surface like fabric there may no measurement.
There are other types of distance sensors that are more accurate for projects where needed, this is a cheap < £5 sensor, while more accurate ones are over £100.
Wiring
Wiring up buttonsthe and switchessensor is simple:
- Power (VCC to 5V)
- Ground (GND to GND)
- Echo to digital pin 12
- Trigger to digital pin 13
Additionally in this diagram there is a LED attached to digital pin 13 for the getting started example code, however this isn't required for other projects.
Getting started
This example turns on an LED when the distance measured is less than 50cm and back off when the distance goes over 60cm.
#include <HCSR04.h>
// Initialize sensor that uses digital pins 13 and 12.
UltraSonicDistanceSensor distanceSensor(13, 12);
void setup () {
Serial.begin(9600); //initialize serial connection so that we could print values from sensor.
}
void loop () {
// Every 0.5 second, do a measurement using the sensor and print the distance in cm.
Serial.println(distanceSensor.measureDistanceCm());
delay(500);
}
To use this code you will need the HCSR04 Library by Martin Sosic.
We have a tutorial on how to install a library here.