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

  1. Power (VCC to 5V)
  2. Ground (GND to GND)
  3. Echo to digital pin 8
  4. Trigger to digital pin 7

hcsr04.png

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

#define trigPin  7
#define echoPin 8
#define maxDistance 400

NewPing sonar( trigPin, echoPin, maxDistance);

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

void loop() {
  Serial.println( sonar.ping_cm() );
  delay( 100 );
}

To use this code you will need the NewPing Library.

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

Back to top