In this exercise, we get acquainted with the distance sensor HC-SR04. We connect it to our cheap Arduino Nano. Before you start with this exercise, we assume that you have already performed the Arduino Blink . As soon as you are finished with this, you can continue with an exciting follow-up project such as the Arduino Stopauto.

We will follow a piece of this example: – but first read on how we do this.

Adding the library and the examples we want to use: In the Arduino IDE, choose Sketch > Include Library > Manage Libraries from the menu… and then in the search box, tap the word “Ultrasonic”. Install Martin Sosic’s HCSR04 library.

Then choose in the IDE for examples: HCSR04 > simple

You now see the code of the example:

#include <HCSR04.h>

UltraSonicDistanceSensor distanceSensor(13, 12);  // Initialize sensor that uses digital pins 13 and 12.

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

void loop () {
    // Every 500 miliseconds, do a measurement using the sensor and print the distance in centimeters.


We see that in the example pin 13 and 12 are used, and on we read how to connect the sensor:

Vcc to 5V
trig to digital pin 13
echo to digital pin 12

You can also see in the example that information is written to “Serial”, which runs via the usb cable to your computer.

You open the Arduino IDE, connect the Arduino Nano, and see if your connection works by sending a blink to the Arduino.

Connect the sensor, and send the sample program to your Arduino Nano.

In the upper right corner of your Arduino IDE you see a square button with a magnifying glass for the Serial monitor. Open the serial monitor. Do you see that different distances are shown? Is there a different processing speed for different distances?

Think about what kind of application you would like to build with this sensor.