Check the 34 other Arduino tutorials

I think it is important that Bas on Tech can be used by everyone free of charge.

Help me ensure the future of Bas on Tech. Your donation will be used for hosting, videos and maintenance, among other things.

Thank you in advance!

#7 · HC-SR04 ultrasonic distance sensor


Introduction

Curious about how to read an ultrasonic sound sensor? In this Arduino tutorial for beginners I explain this exactly 😃

Course material

At the bottom of this page you'll find the course material button. This button allows you to download the code, circuit diagram and other files relevant to this Arduino tutorial.

Ultrasonic sound

Ultrasonic sound is sound that we humans cannot hear. The frequency is simply too high. There are animals that can hear this sound, such as bats, dogs and dolphins. For example, a dog whistle emits an ultrasonic sound.

HC-SR04 ultrasonic sensor

In this lesson we will use the HC-SR04 ultrasonic distance sensor This uses ultrasound to determine a distance.

HR-SR04 ultrasonic distance sensor
HR-SR04 ultrasonic distance sensor

The sensor has two "eyes", each marked with a letter:

  • T is the transmitter (Transmitter)
  • R is the receiver (Receiver)

Objects reflect ultrasound. Because this sensor can send and receive sound, it is possible to calculate the distance. He does this by transmitting sound and then measuring how long it takes the receiver to hear this sound again. It is known how much distance sound can travel in a certain time. In this way we can calculate the approximate distance based on the elapsed time between sending and receiving.

In addition to the well-known 5V and GND, the sensor has two special pins: Trig and Echo. When the trigger pin is HIGH the HC-SR04 sensor will start transmitting. The echo pin becomes HIGH when the receiver receives sound.

💡 It is important that we soon divide the calculated distance by 2. After all, the sound first went to the object and then reflected back. So the distance has been covered twice.

The circuit

HHR-SR04 ultrasonic distance sensor connected to the Arduino
HHR-SR04 ultrasonic distance sensor connected to the Arduino

Push the HR-SR04 into the breadboard and connect the following jumper wires to:

  • The 5V on the Arduino -> the left pin of the sensor
  • The 12 on the Arduino -> the trig pin of the sensor
  • The 8 on the Arduino -> the echo pin of the sensor
  • The GND on the Arduino -> the right pin of the sensor

Arduino Code

We start the code by defining three variables:

1 const int trigPin = 12;
2 const int echoPin = 8;
3 
4 float duration;
5 float distance;
  • trigPin is the pin to which we connected the trigger
  • echoPin is the pin we connected the echo to
  • duration is the elapsed time
  • distance is the measured distance

setup()

1 void setup() {
2     Serial.begin(9600);
3     pinMode(trigPin, OUTPUT);
4     pinMode(echoPin, INPUT);
5 }

First, we initialize the serial monitor. Then we set the trigPin as the output and the echoPin as the input.

loop()

1 // repeat infinitely
2 void loop() {
3     digitalWrite(trigPin, LOW);
4     delayMicroseconds(2);
5 
6     digitalWrite(trigPin, HIGH);
7     delayMicroseconds(10);
8     digitalWrite(trigPin, LOW);
9 
10     duration = pulseIn(echoPin, HIGH);              
11     distance = (duration * 0.0343) / 2;
12                                      
13     Serial.print("Afstand: ");
14     Serial.println(distance);
15 
16     delay(100);                     
17 }

delayMicroseconds()

In the code we see a new function delayMicroseconds(). Earlier we used delay() which pauses for a few milliseconds. The delayMicroseconds() is even more precise and pauses in microseconds.

The code

The loop() function consists of 4 parts:

  • Prepare trigPin
  • Start measurement
  • Calculate duration and distance
  • Send data to serial monitor

We'll start by making sure that trigPin is set to LOW and not transmitting. After that, we can start to emit 10 microseconds of ultrasound. We do this by setting trigPin to HIGH and then pausing with delayMicroseconds(). Then we stop sending by setting the trigPin to LOW again. The sound has been sent away and now we wait for the sound to come back.

pulseIn()

The pulseIn() function is a special function to measure the length of a pulse. It can be a switch from LOW to HIGH, or vice versa. pulseIn() has 3 parameters, the last of which is optional:

  • pin number from which the pulse is read
  • the type of pulse to read from: LOW or HIGH
  • number of microseconds to wait for the pulse to start

If we look in our code we see:

1  pulseIn(echoPin, HIGH);

This means we wait for the echoPin to go from LOW to HIGH. As shown schematically below:

pulseIn() met Pulsetype HIGH
pulseIn() with Pulsetype HIGH

As soon as this change is detected, the elapsed time measurement begins. The timer stops when the value changes back from HIGH to LOW.

We can also do the opposite:

1 pulseIn(echoPin, LOW);

In this case we wait for the pin to change from HIGH to LOW and then start the measurement.

pulseIn() met Pulsetype LOW
pulseIn() with Pulsetype LOW

Measure distance

Now that we know how pulseIn() works, the code below is easy to understand.

1 duration = pulseIn(echoPin, HIGH);
2 distance = (duration * 0.0343) / 2;

We start by measuring how long the sound has been traveling. To do this, we put pulseIn() on the echoPin, and wait for the sound to come back. We now know the time between sending and receiving the sound. We store this in duration.

To calculate the distance traveled we first need to know the speed of sound. This is 343 meters per second. This equals 0.000343 meters per microsecond.

However, we want to know the number of centimeters per microsecond. 1 meter is 100 centimeters. So we multiply 0.000343 by 100. This gives us 0.0343 centimeters per second.

Since the sound travels the distance twice, we need to divide this value by 2 to get the distance in centimeters.

🎓 By how much should we have multiplied to get the distance in millimeters?

Upload code to Arduino

Our program is now ready to be sent to the Arduino. Then open the serial monitor:

Tools â–¸ Serial Monitor

Measured distance displayed in serial monitor
Measured distance displayed in serial monitor

Now move your hand away from the sensor and towards the sensor. You should see the distance to your hand in the serial monitor.

#7 · HC-SR04 ultrasonic distance sensor schakelschema

Bas van Dijk

About Bas on Tech


My name is Bas van Dijk, entrepreneur, software developer and maker. With Bas on Tech I share video tutorials with a wide variety of tech subjects i.e. Arduino and 3D printing.

Years ago, I bought my first Arduino with one goal: show text on an LCD as soon as possible. It took me many Google searches and digging through various resources, but I finally managed to make it work. I was over the moon by something as simple as an LCD with some text.

With Bas on Tech I want to share my knowledge so others can experience this happiness as well. I've chosen to make short, yet powerful YouTube videos with a the same structure and one subject per video. Each video is accompanied by the source code and a shopping list.