Arduino Nano - Ultrasonic Sensor

This tutorial instructs you how to use Arduino Nano and ultrasonic sensor to measure the distance to obstacles or objects. In detail, we will learn:

Hardware Preparation

1×Arduino Nano
1×USB A to Mini-B USB cable
1×Ultrasonic Sensor
1×Jumper Wires
1×(Optional) 9V Power Adapter for Arduino Nano
1×(Recommended) Screw Terminal Adapter for Arduino Nano

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you. We appreciate your support.

Overview of Ultrasonic Sensor

The HC-SR04 ultrasonic sensor is used to measure the distance to an object by using ultrasonic waves.

The Ultrasonic Sensor Pinout

The HC-SR04 ultrasonic sensor has four pins:

  • VCC pin: must be connected to VCC (5V)
  • GND pin: must be connected to GND (0V)
  • TRIG pin: receives a control signal (pulse) from Arduino Nano
  • ECHO pin: sends a signal (pulse) to Arduino Nano. Arduino Nano measures the length of the pulse to calculate the distance.
Ultrasonic Sensor pinout

How It Works

This section includes advanced information that may be overwhelming. If you are unsure about the content, feel free to skip it and move on to the next sections.
  • The Arduino Nano produces a 10-microsecond pulse on the TRIG pin, which causes the ultrasonic sensor to emit ultrasonic waves.
  • When the waves hit an obstacle, they are reflected back.
  • The ultrasonic sensor is able to detect the reflected wave and measure its travel time.
  • The sensor then generates a pulse to the ECHO pin, with a duration equal to the travel time of the ultrasonic wave.
  • The Arduino Nano measures the pulse duration in the ECHO pin and calculates the distance between the sensor and the obstacle.

How to Get Distance From Ultrasonic Sensor

To calculate the distance from the ultrasonic sensor, We just need to write Arduino code to do two steps (1 and 6 on How It Works):

  • Arduino Nano generates a 10-microsecond pulse on the TRIG pin.
  • Arduino Nano measures the pulse duration in the ECHO pin.
  • Then, Arduino Nano uses the measured pulse duration to calculate the distance between the sensor and obstacle.

Distance Calculation

We have:

  • The travel time of the ultrasonic wave (µs): travel_time = pulse_duration
  • The speed of the ultrasonic wave: speed = SPEED_OF_SOUND = 340 m/s = 0.034 cm/µs

So:

  • The travel distance of the ultrasonic wave (cm): travel_distance = speed × travel_time = 0.034 × pulse_duration
  • The distance between sensor and obstacle (cm): distance = travel_distance / 2 = 0.034 × pulse_duration / 2 = 0.017 × pulse_duration

Arduino Nano - Ultrasonic Sensor

The Arduino Nano's pins can produce a 10-microsecond pulse and measure the pulse duration. This allows us to use two of the Arduino Nano's pins to determine the distance from the ultrasonic sensor to an object. We just need to:

  • Connect one pin of Arduino Nano to the TRIG pin of ultrasonic sensor. This Arduino Nano pin is used to generate a 10µs pulse to the TRIG pin of the sensor
  • Connect another pin of Arduino Nano to the ECHO pin of ultrasonic sensor. This Arduino Nano pin is used to measure the pulse from the sensor

Wiring Diagram

The wiring diagram between Arduino Nano and ultrasonic sensor

This image is created using Fritzing. Click to enlarge image

How To Program For Ultrasonic Sensor

digitalWrite(3, HIGH); delayMicroseconds(10); digitalWrite(3, LOW);
  • Measure the pulse duration (in microseconds) on Arduino's pin 2 by utilizing the pulseIn() function. For instance:
duration_us = pulseIn(2, HIGH);
  • Calculate the distance (cm):
distance_cm = 0.017 * duration_us;

Arduino Nano Code

/* * This Arduino Nano code was developed by newbiely.com * * This Arduino Nano code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-nano/arduino-nano-ultrasonic-sensor */ #define TRIG_PIN 3 // The Arduino Nano pin connected to TRIG pin of ultrasonic sensor #define ECHO_PIN 2 // The Arduino Nano pin connected to ECHO pin of ultrasonic sensor float duration_us, distance_cm; void setup() { // begin serial port Serial.begin (9600); // Configure the trigger pin to output mode pinMode(TRIG_PIN, OUTPUT); // Configure the echo pin to input mode pinMode(ECHO_PIN, INPUT); } void loop() { // Produce a 10-microsecond pulse to the TRIG pin. digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Measure the pulse duration from the ECHO pin duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance distance_cm = 0.017 * duration_us; // print the value to Serial Monitor Serial.print("distance: "); Serial.print(distance_cm); Serial.println(" cm"); delay(500); }

Detailed Instructions

  • Copy the code and open it with the Arduino IDE.
  • Then, click the Upload button in the Arduino IDE to compile and upload the code to the Arduino Nano.
How to upload code to Arduino Nano
  • Open the Serial Monitor
  • Place your hand in front of the ultrasonic sensor
  • Check out the distance from the sensor to your hand being displayed on the Serial Monitor
COM6
Send
distance: 29.4 cm distance: 27.6 cm distance: 26.9 cm distance: 17.4 cm distance: 16.9 cm distance: 14.3 cm distance: 15.6 cm distance: 13.1 cm
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

How to Filter Noise from Distance Measurements of Ultrasonic Sensor

The measurement result from an ultrasonic sensor may contain noise, which can lead to unwanted operations in some applications. To remove the noise, we can use the following algorithm:

  1. Take multiple measurements and store them in an array
  2. Sort the array in ascending order
  3. Filter out noise by:
    • The smallest samples are considered as noise and should be ignored
    • The biggest samples are considered as noise and should be ignored
    • The average of the middle samples should be taken

    The below example code takes 20 measurements:

    • Ignore the five smallest samples.
    • Ignore the five biggest samples.
    • Get the average of the 10 middle samples from the fifth to the fourteenth.
    /* * This Arduino Nano code was developed by newbiely.com * * This Arduino Nano code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-nano/arduino-nano-ultrasonic-sensor */ #define TRIG_PIN 3 // The Arduino Nano pin connected to TRIG pin of ultrasonic sensor #define ECHO_PIN 2 // The Arduino Nano pin connected to ECHO pin of ultrasonic sensor float filterArray[20]; // array to store data samples from sensor float distance; // store the distance from sensor void setup() { // begin serial port Serial.begin (9600); // Configure the trigger and echo pins to output mode pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); } void loop() { // 1. TAKING MULTIPLE MEASUREMENTS AND STORE IN AN ARRAY for (int sample = 0; sample < 20; sample++) { filterArray[sample] = ultrasonicMeasure(); delay(30); // to avoid untrasonic interfering } // 2. SORTING THE ARRAY IN ASCENDING ORDER for (int i = 0; i < 19; i++) { for (int j = i + 1; j < 20; j++) { if (filterArray[i] > filterArray[j]) { float swap = filterArray[i]; filterArray[i] = filterArray[j]; filterArray[j] = swap; } } } // 3. FILTERING NOISE // + the five smallest samples are considered as noise -> ignore it // + the five biggest samples are considered as noise -> ignore it // ---------------------------------------------------------------- // => get average of the 10 middle samples (from 5th to 14th) double sum = 0; for (int sample = 5; sample < 15; sample++) { sum += filterArray[sample]; } distance = sum / 10; // print the value to Serial Monitor Serial.print("distance: "); Serial.print(distance); Serial.println(" cm"); } float ultrasonicMeasure() { // Produce a 10-microsecond pulse to the TRIG pin. digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // Measure the pulse duration from the ECHO pin float duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance float distance_cm = 0.017 * duration_us; return distance_cm; }

Video Tutorial

Challenge Yourself

Employ an ultrasonic sensor for any of the following projects:

  • Building a collision avoidance system for a remote-controlled car.
  • Establishing the fullness of a dustbin.
  • Tracking the level of a dustbin.
  • Automatically opening and closing a dustbin. Hint: See Arduino Nano - Servo Motor.

Ultrasonic Sensor Applications

  • Avoiding Collisions
  • Detecting Fullness
  • Measuring Level
  • Detecting Proximity