Measure distance with the HC-SR04 ultrasonic sensor

FunduinoPublished on

Entfernung messen und daraus einen Rückfahrwarner bauen

Aufgabe: Miss mit dem Ultraschallsensor HC-SR04 eine Entfernung und lass sie dir im seriellen Monitor anzeigen. Das Projekt funktioniert mit dem Arduino UNO, dem Wemos D1 Mini, dem NodeMCU und dem ESP32-Wroom.

You need this

HC-SR04 Ultrasonic Sensor - distance measurement 2-400 cm, 5 V HC-SR04 Ultrasonic Sensor - distance measurement 2-400 cm, 5 V 2,26 € *Item no. FUN-1010564About the product — HC-SR04 Ultrasonic Sensor - distance measurement 2-400 cm, 5 V
Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino 11,12 € *Item no. F23107480About the product — Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino
830-point Breadboard - solderless breadboard for Arduino 830-point Breadboard - solderless breadboard for Arduino 2,90 € *Item no. FUN-1010553About the product — 830-point Breadboard - solderless breadboard for Arduino
Breadboard Cables Male-to-Male - 40 Pieces, 20 cm Breadboard Cables Male-to-Male - 40 Pieces, 20 cm 1,74 € *Item no. FUN-1010558About the product — Breadboard Cables Male-to-Male - 40 Pieces, 20 cm

All 4 parts together 18,02 € *Ready to ship immediately · Delivery time: 1-3 business days

* All prices include statutory VAT, plus shipping costs.

Choose a microcontroller

Pins, schematic, and sketch in the steps change with your selection. It remains saved.

How does the HC-SR04 ultrasonic sensor work?

The sensor has four connections: VCC (+), Trig (send signal), Echo (receive reflected signal), and GND (–).

The ultrasonic sensor emits a short sound pulse that travels through the air at the speed of sound. When it hits an object, it is reflected and returns as an echo. The sensor calculates the distance to the object from the time between sending and receiving the pulse.

In the program, the pulseIn() command sends a HIGH signal, starts a timer, and waits for the signal to return (with a LOW value). The timer then stops, and the time between sending (trigger) and returning (echo) is measured in microseconds.

Sound travels through air at 343.20 m/s. Converted: 343.20 m = 34,320 cm, divided by 1,000 gives 34.32 cm per millisecond, divided by 1,000 again gives 0.03432 cm per microsecond.

In the program, write the number with a decimal point instead of a comma: 0.03432

HC-SR04 ultrasonic sensor with four pins
The HC-SR04 ultrasonic sensor
Schematic diagram of ultrasonic distance measurement
Measuring principle: sound pulse, reflection, echo (image source: microsonic.de)
1 / 2

Display distance in the serial monitor

The ultrasonic sensor measures the distance and displays the result in the serial monitor. Select your board below - the wiring diagram and sketch will adjust accordingly.

Serial monitor with distance values in centimeters
The measured distance in the serial monitor
Wiring the HC-SR04 to the Arduino UNO
Arduino UNO schematic
Arduino UNO
// Pin für den Sender
int SENDEN = 7;
// Pin für das vom Objekt reflektierte Signal
int ECHO = 6;
// Variable für die Speicherung der Entfernung
long Entfernung = 0;
void setup()
{
  pinMode(SENDEN, OUTPUT);
  pinMode(ECHO, INPUT);
  // Seriellen Monitor starten
  Serial.begin(9600);
}
void loop()
{
  // Sender kurz ausschalten, um Störungen des Signals zu vermeiden
  digitalWrite(SENDEN, LOW);
  delay(5);
  // Signal für 10 Mikrosekunden senden, danach wieder ausschalten
  digitalWrite(SENDEN, HIGH);
  delayMicroseconds(10);
  digitalWrite(SENDEN, LOW);
  // pulseIn -> Zeit messen, bis das Signal zurückkommt
  long Zeit = pulseIn(ECHO, HIGH);
  // Entfernung in cm berechnen
  // Zeit/2 -> nur eine Strecke
  Entfernung = (Zeit / 2) * 0.03432;
  delay(500);
  // nur Entfernungen < 100 anzeigen
  if (Entfernung < 100)
  {
    // Messdaten anzeigen
    Serial.print("Entfernung in cm: ");
    Serial.println(Entfernung);
  }
}

Download: arduino-uno.ino

Board in the Arduino IDEArduino Uno

You don’t need an additional board package for this. The UNO is included in the Arduino IDE by default.

Reverse warning buzzer

You also connect an LED and a piezo speaker. The closer the object gets, the faster the LED flashes and the shorter the intervals between the tones become.

Instead of an if statement, the program code uses a switch-case block to check value ranges. The variable being checked goes in parentheses after switch; each case block defines a range of values.

When writing value ranges, use a space before and after the three dots, and make sure the ranges do not overlap.

HC-SR04 with LED and piezo buzzer on the Arduino UNO
Wiring diagram for a reverse beeper on the Arduino UNO
Arduino UNO
```cpp
int LED = 3;
int SPEAKER = 4;
int ECHO = 6;
int TRIGGER = 7;
long Distance = 0;
void setup()
{
  pinMode(TRIGGER, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(SPEAKER, OUTPUT);
  pinMode(LED, OUTPUT);
}
void loop()
{
  // Briefly turn off the transmitter to avoid signal interference
  digitalWrite(TRIGGER, LOW);
  delay(5);
  // Send the signal
  digitalWrite(TRIGGER, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER, LOW);
  // pulseIn -> measure the time until the signal returns
  long Time = pulseIn(ECHO, HIGH);
  // Calculate distance in cm
  // Time/2 -> one-way distance only
  Distance = (Time / 2) * 0.03432;
  switch (Distance)
  {
    case 13 ... 15:
      tone(SPEAKER, 1000, 2);
      digitalWrite(LED, HIGH);
      delay(50);
      digitalWrite(LED, LOW);
      delay(500);
      break;
    case 11 ... 12:
      tone(SPEAKER, 1000, 2);
      digitalWrite(LED, HIGH);
      delay(50);
      digitalWrite(LED, LOW);
      delay(400);
      break;
    case 9 ... 10:
      tone(SPEAKER, 1000, 2);
      digitalWrite(LED, HIGH);
      delay(50);
      digitalWrite(LED, LOW);
      delay(300);
      break;
    case 7 ... 8:
      tone(SPEAKER, 1000, 2);
      digitalWrite(LED, HIGH);
      delay(50);
      digitalWrite(LED, LOW);
      delay(200);
      break;
    case 5 ... 6:
      tone(SPEAKER, 1000, 2);
      digitalWrite(LED, HIGH);
      delay(50);
      digitalWrite(LED, LOW);
      delay(100);
      break;
    case 2 ... 4:
      tone(SPEAKER, 1000);
      digitalWrite(LED, HIGH);
      break;
  }
}
```

Download: arduino-uno.ino

Board in the Arduino IDEArduino Uno

You don’t need an additional board package for this. The UNO is included in the Arduino IDE by default.

Rate the instructions

Comments

Ask a question or share an experience

Contact us if something doesn’t work. Please include your board and the error message.

We review every comment before publication. Your email address remains with us.