Arduino UNO R4 - Ultrasonic Sensor

This tutorial instructs you how to use the ultrasonic sensor and Arduino UNO R4 to measure distance to an object. In detail, we will learn:

Arduino UNO R4 ultrasonic sensor

Hardware Preparation

1×Arduino UNO R4 WiFi
1×Arduino UNO R4 Minima (Alternatively)
1×USB Cable Type-C
1×Ultrasonic Sensor
1×Jumper Wires
1×(Recommended) Screw Terminal Block Shield for Arduino UNO R4
1×(Recommended) Breadboard Shield For Arduino UNO R4
1×(Recommended) Enclosure For Arduino UNO R4

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
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.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Ultrasonic Sensor

The HC-SR04 ultrasonic sensor measures the distance to objects using sound waves. It sends out a sound wave that humans cannot hear, and then listens for the echo when the sound wave bounces back from an object. By measuring the time it takes for the sound wave to return, the sensor can calculate how far away the object is.

Pinout

The ultrasonic sensor HC-SR04 comes with four pins:

  • VCC pin: Connect this pin to VCC (5V).
  • GND pin: Connect this pin to GND (0V).
  • TRIG pin: Connect this pin to Arduino UNO R4 to send control signals (pulses).
  • ECHO pin: This pin sends signals (pulses) back to Arduino UNO R4. The Arduino UNO R4 then calculates the duration of these pulses to determine distance.
Ultrasonic Sensor Pinout
image source: diyables.io

Wiring Diagram

The wiring diagram between Arduino UNO R4 Ultrasonic Sensor

This image is created using Fritzing. Click to enlarge image

Arduino UNO R4 Code

#define TRIG_PIN 9 // The Arduino UNO R4 pin connected to the ultrasonic sensor's TRIG pin #define ECHO_PIN 8 // The Arduino UNO R4 pin connected to the ultrasonic sensor's ECHO pin 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() { // generate 10-microsecond pulse to TRIG pin digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // measure duration of pulse from 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

Follow these instructions step by step:

  • If this is your first time using the Arduino Uno R4 WiFi/Minima, refer to the tutorial on setting up the environment for Arduino Uno R4 WiFi/Minima in the Arduino IDE.
  • Wire the components according to the provided diagram.
  • Connect the Arduino Uno R4 board to your computer using a USB cable.
  • Launch the Arduino IDE on your computer.
  • Select the appropriate Arduino Uno R4 board (e.g., Arduino Uno R4 WiFi) and COM port.
  • Copy the code above and open it with Arduino IDE
  • Click the Upload button in Arduino IDE to send the code to Arduino UNO R4
Arduino IDE - How to Upload Code
  • Open the Serial Monitor.
  • Wave your hand in front of the ultrasonic sensor.
  • Check the distance between your hand and the sensor 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

The explanation is in the comments of the Arduino code above.

How to Filter Noise from Distance Measurements of Ultrasonic Sensor

The reading from the ultrasonic sensor includes noise. In some cases, this noisy data can lead to incorrect functioning. We can eliminate the noise using this method:

  • Take several measurements and save them in an array.
  • Sort the array from smallest to largest.
  • Remove noise from the data:
    • Disregard the smallest values as they are noise.
    • Disregard the largest values as they are noise.
    • Calculate the average using the remaining middle values.

    The example code below takes 20 measurements.

    • Ignore the five smallest samples and the five largest samples as they are seen as noise. Calculate the average of the ten middle samples, from the 5th to the 14th.
    /* * This Arduino UNO R4 code was developed by newbiely.com * * This Arduino UNO R4 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-ultrasonic-sensor */ #define TRIG_PIN 9 // The Arduino UNO R4 pin connected to the ultrasonic sensor's TRIG pin #define ECHO_PIN 8 // The Arduino UNO R4 pin connected to the ultrasonic sensor's ECHO pin 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() { // generate 10-microsecond pulse to TRIG pin digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // measure duration of pulse from ECHO pin float duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance float distance_cm = 0.017 * duration_us; return distance_cm; }

Video Tutorial

Ultrasonic Sensor Applications

  • Avoiding Collisions
  • Detecting Fullness
  • Measuring Level
  • Detecting Closeness

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!