Skip to main content

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 up buttons and switches is simple:

  1. Power (VCC to 5V)
  2. Ground (GND to GND)
  3. Echo to digital pin 12
  4. 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.

To use this code you will need the HCSR04 Library by Martin Sosic.

We have a tutorial on how to install a library here.