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 812
  4. Trigger to digital pin 713


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 <NewPing.HCSR04.h>

#define// trigPinInitialize 7sensor #definethat echoPinuses 8digital #definepins maxDistance13 400and NewPing12.
sonar(UltraSonicDistanceSensor trigPin,distanceSensor(13, echoPin, maxDistance)12);  

void setup(setup () {
    Serial.begin(9600);  9600//initialize );serial connection so that we could print values from sensor.

void loop(loop () {
    // Every 0.5 second, do a measurement using the sensor and print the distance in cm.
    Serial.println( sonar.ping_cm(distanceSensor.measureDistanceCm() );
    delay( 100 )500);

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

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