HC-SR04 Ultrasonic Sensor Modules

Table of Contents

This comprehensive guide is your one – stop resource to explore everything there is to know about the HC-SR04. We’ll start from the very basics, understanding its fundamental working principle, which is the key to unlocking its potential. Then, we’ll move on to cover important aspects such as its key specifications, how to interface it with popular microcontrollers, and even delve into advanced usage scenarios. By the end of this guide, you’ll be well – equipped to leverage the full potential of the HC-SR04 in your own projects.

What is HC-SR04 ultrasonic sensor module?

The HC-SR04 ultrasonic sensor module is a remarkable and highly versatile device that has carved a niche for itself in the vast landscape of electronics projects. What makes it truly stand out is its cost-effectiveness, a feature that makes it accessible to a wide range of users, from budget-conscious hobbyists to professionals looking for an affordable solution for their projects.

Front and back view of HC SR04 Ultrasonic Sensor Module
Front and back view of HC - SR04 Ultrasonic Sensor Module

Technical Specifications

Understanding the technical specifications of the HC – SR04 ultrasonic sensor module is crucial for any project implementation. Here’s the table of tech spec:

Operating Voltage
+5V DC (4.5V to 5.5V)
Operating Current
~15mA (Standby: ~2mA)
Range
2cm to 400cm (0.8" to 13ft)
Accuracy
±3mm (Best case, varies with environment)
Resolution
0.3cm (1mm theoretically possible with calibration)
Angle of Detection
~15° cone angle
Trigger Input Signal
10μs HIGH pulse to initiate ranging
Echo Output Signal
Pulse width proportional to distance: 1μs = 0.017cm (based on sound speed 340m/s)
Maximum Frequency
40kHz ultrasonic frequency
Measurement Cycle
≥60ms (to avoid interference between measurements)
Operating Temperature
-15°C to +60°C (5°F to 140°F)
Dimensions
45mm × 20mm × 15mm (sensor module)
Weight
~5g (module only)

Explanation:

  1. Range: The HC – SR04 has an operational range spanning from 2 cm to 400 cm (0.8 in to 157 in). This relatively wide range makes it suitable for a variety of applications. For example, in a small – scale robotics project where the robot needs to navigate in a room, the 2 – 400 cm range can effectively detect nearby furniture or walls. In a larger – scale industrial application, it can be used to measure the distance between machinery components within this range. However, it’s important to note that the accuracy may vary slightly at the extreme ends of this range.
  1. Resolution: With a resolution of 0.3 cm, the HC – SR04 can provide fairly precise distance measurements. This level of precision is sufficient for most hobbyist and many industrial applications. In a 3D – printing – related project where the sensor is used to detect the distance to the print bed for auto – leveling, the 0.3 cm resolution can ensure that the printer head is at the correct height above the bed, resulting in high – quality prints.
  1. Power Supply: It operates on a 5V DC power supply. During operation, it draws an operating current of 15mA, which is relatively low – power consumption. In standby mode, the current draw is even less, less than 2mA. This makes it an energy – efficient choice for battery – powered projects. For instance, in a battery – operated IoT sensor node that uses the HC – SR04 for distance sensing, the low – power consumption ensures that the battery can last for an extended period.
  1. Operating Angle: The operating angle of the HC – SR04 is less than 15°. This means that the sensor has a relatively narrow field of view. It is most effective at detecting obstacles that are directly in front of it. In a smart – home security system where the sensor is used to detect intruders approaching a door, the narrow operating angle allows for focused detection of objects coming straight towards the sensor, reducing false alarms from objects in the peripheral area.
  1. Interface: The module features a 4 – pin interface, which includes VCC, GND, Trig, and Echo pins. This simple interface design makes it easy to connect to various microcontrollers and other electronic components.

Pinout Explained

Pin 1
Label
VCC
Function
Power Supply (Positive)
Voltage
5V DC
Connection
Arduino: 5V
Raspberry Pi: 5V (Common ground with module)
Pin 2
Label
Trig (Trigger)
Function
Trigger Input
▶ 10μs High Pulse to Start Measurement
▶ Low Level to Reset
Connection
Arduino: Any Digital Pin (e.g., D2)
Raspberry Pi: Any GPIO (e.g., GPIO17)
Pin 3
Label
Echo
Function
Echo Output
▶ High Duration = Round-Trip Time of Ultrasonic Waves
▶ Max High Time: 38ms (Timeout for No Obstacle)
Connection
Arduino: Any Digital Pin (e.g., D3)
Raspberry Pi: GPIO with **Voltage Divider** (5V→3.3V)
⚠️ Direct 5V Echo to Raspberry Pi may damage GPIO! Use 1kΩ + 2kΩ voltage divider.
Pin 4
Label
GND
Function
Power Ground (Common Ground)
Connection
Arduino/GND
Raspberry Pi/GND

Explanation:

The VCC pin is responsible for powering the module. Connecting it to a stable 5V power source, preferably from the microcontroller’s 5V output, ensures that the module functions correctly. A stable power supply is crucial for accurate readings. If the power supply is unstable, it can lead to inconsistent distance measurements. For example, if there are voltage spikes or drops in the power supply to the HC – SR04, the sensor may emit incorrect ultrasonic pulses or misinterpret the received echoes, resulting in inaccurate distance calculations.
The GND pin provides the necessary ground connection. It completes the electrical circuit and helps in maintaining a stable reference voltage for the module. Without a proper ground connection, the module may not function at all or may produce erratic results. In an Arduino – based project, the GND pin of the HC – SR04 is typically connected to the GND pin of the Arduino board to ensure a common ground reference.
The Trig pin is where the magic starts. When a 10μs high – level pulse is sent to this pin, it triggers the ultrasonic transmitter to send out the 8 – pulse burst of 40kHz ultrasonic waves. In a Python – based Raspberry Pi project, you can use the GPIO (General – Purpose Input/Output) library to generate this 10μs high – level pulse. This simple digital input mechanism allows for easy control of the distance – measurement process.

The Echo pin is the key to obtaining the distance information. Once the ultrasonic waves are sent out, the Echo pin goes high. It remains high until the reflected waves are received by the ultrasonic receiver. The duration for which the Echo pin is high is directly proportional to the time it takes for the ultrasonic waves to travel to the obstacle and back. By measuring this time duration, we can calculate the distance to the obstacle using the formula Distance ( cm ) = Time ( μs ) × 0.0343 2 . In a C++-based Arduino project, you can use the pulseIn() function to measure the duration of the high-level pulse on the Echo pin.

Core Components and Working Principle

Key Components

To truly understand how the HC – SR04 ultrasonic sensor module functions, it’s essential to first familiarize ourselves with its core components. Each part plays a distinct and crucial role in the overall operation of the module.

  1. Ultrasonic Transmitter: This is the component responsible for the initial step in the distance – measuring process. It emits ultrasonic waves at a frequency of 40kHz. These high – frequency waves are inaudible to the human ear but are the key to the sensor’s operation. When triggered, the transmitter sends out these waves into the surrounding environment. Think of it as a powerful speaker that emits sound waves at a frequency far beyond what we can hear. In a robotics application, for example, the ultrasonic transmitter on a robot would send out these 40kHz waves in the direction the robot is moving, preparing to detect any obstacles in its path.
  1. Ultrasonic Receiver: As the name implies, the ultrasonic receiver’s job is to capture the ultrasonic waves that have been reflected back from any obstacles in the sensor’s range. Once the transmitter sends out the waves, they travel through the air until they hit an object. The waves then bounce back, and it’s the receiver’s task to pick up these reflected waves. It’s like a highly sensitive microphone that can detect the faintest echoes of the ultrasonic waves. In a home automation system where the HC – SR04 is used to detect the presence of a person in a room, the receiver would catch the waves that bounce back from the person’s body.
  1. Control Circuit: This is the brains behind the operation. The control circuit manages the entire signal – processing sequence. It coordinates the actions of the transmitter and the receiver. When it receives a trigger signal, it instructs the transmitter to emit the ultrasonic waves. Then, it carefully monitors the receiver for the incoming reflected waves. Once the waves are received, the control circuit calculates the time it took for the waves to travel to the obstacle and back. Based on this time and the known speed of sound in air, it computes the distance to the obstacle. In an industrial setting, the control circuit in an HC – SR04 used for automated machinery would precisely manage these operations to ensure accurate distance measurements for the proper functioning of the machinery.

How It Works

Now that we know about the key components, let’s take a step – by – step look at how the HC – SR04 actually measures distance.

Trigger Signal: 

The process begins with a trigger signal. When a 10μs high pulse is applied to the Trig (Trigger) pin of the HC – SR04 module, it’s like giving the sensor a “start” command. This short but significant electrical pulse initiates the entire distance – measuring sequence. For instance, in an Arduino – based project, you would use a simple line of code to send this 10μs high pulse to the Trig pin of the HC – SR04, telling it to begin the measurement process.

Wave Propagation: 

Once triggered, the ultrasonic transmitter swings into action. The module sends out a burst of 8 ultrasonic pulses at a frequency of 40kHz. These pulses are like a series of invisible “sonic bullets” that shoot out into the environment. After sending these pulses, the module then enters a waiting state, patiently waiting for the waves to hit an obstacle and bounce back. In a real – world scenario, if you were using the HC – SR04 to measure the distance to a wall in a room, the 8 pulses would travel towards the wall, spreading out in a cone – like shape with a relatively narrow angle of about 15 degrees.

Echo Detection: 

The Echo pin is the key to detecting the reflected waves. As soon as the ultrasonic waves are sent out, the Echo pin goes high. This is the sensor’s way of indicating that it has started the measurement process. Then, it waits for the reflected waves to return. When the ultrasonic receiver captures the reflected waves, the Echo pin goes low. The duration for which the Echo pin remains high is equal to the round – trip travel time of the ultrasonic waves. In a Raspberry Pi project, you would use a function to measure the time the Echo pin is high, which is a crucial step in calculating the distance.

Distance Calculation:

Distance Calculation: The final step is to calculate the distance to the obstacle. The formula for calculating the distance in centimeters is Distance (cm) = Time ((μs)) × 0.0343 2 . The factor 0.0343 comes from the speed of sound in air, which is approximately 343 m/s. Since the waves travel to the obstacle and back (a round-trip), we divide the total distance traveled by 2 to get the one-way distance to the obstacle. For example, if the time measured for the Echo pin to be high is 2000μs, then the distance would be calculated as 2000 × 0.0343 2 = 34.3 cm. This calculation is the same whether you're using the HC-SR04 in a simple hobbyist project or a complex industrial application.

Interfacing with Popular Microcontrollers

Arduino Setup Guide

Wiring Diagram

Connecting the HC – SR04 ultrasonic sensor module to an Arduino is a straightforward process. Here’s how you can do it:

  • VCC: Connect the VCC pin of the HC – SR04 to the 5V pin of the Arduino. This provides the necessary power to the sensor module. A stable 5V power supply from the Arduino ensures that the sensor functions optimally.
  • GND: The GND (Ground) pin of the HC – SR04 should be connected to the GND pin of the Arduino. This establishes a common ground reference for both the sensor and the Arduino, which is crucial for proper electrical communication.
  • Trig: Connect the Trig (Trigger) pin of the HC – SR04 to digital pin 2 of the Arduino. This is the pin where the Arduino will send the 10μs high – level pulse to trigger the distance – measurement process in the HC – SR04.
  • Echo: The Echo pin of the HC – SR04 is connected to digital pin 3 of the Arduino. The Arduino will read the high – duration pulse on this pin to calculate the distance to the obstacle.
Here is a simple wiring diagram to illustrate the connections:
				
					       HC - SR04         Arduino
         VCC ------------ 5V
         GND ------------ GND
         Trig ------------ Digital Pin 2
         Echo ------------ Digital Pin 3
				
			

Code Example

Here is a basic Arduino code example to get you started with measuring distance using the HC – SR04:
				
					const int trigPin = 2;
const int echoPin = 3;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

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

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(500);
}
				
			
In the setup function, we first initialize the serial communication at a baud rate of 9600, which allows us to view the distance readings in the Arduino Serial Monitor. Then, we set the trigPin as an output pin and the echoPin as an input pin.
In the loop function, we start by setting the trigPin to LOW for 2 microseconds to ensure a clean start. Then, we set it HIGH for 10 microseconds to trigger the ultrasonic transmitter in the HC – SR04. After that, we set the trigPin back to LOW.
The pulseIn function is then used to measure the duration of the high – level pulse on the echoPin. This duration represents the time it took for the ultrasonic waves to travel to the obstacle and back. We then calculate the distance using the formula distance = duration * 0.0343 / 2, where 0.0343 is the speed of sound in cm/μs and we divide by 2 because the waves travel to the obstacle and back.
Finally, we print the calculated distance to the Serial Monitor and add a 500 – millisecond delay before the next measurement.

In the setup function, we first initialize the serial communication at a baud rate of 9600, which allows us to view the distance readings in the Arduino Serial Monitor. Then, we set the trigPin as an output pin and the echoPin as an input pin.

In the loop function, we start by setting the trigPin to LOW for 2 microseconds to ensure a clean start. Then, we set it HIGH for 10 microseconds to trigger the ultrasonic transmitter in the HC-SR04. After that, we set the trigPin back to LOW.

The pulseIn() function is then used to measure the duration of the high-level pulse on the echoPin. This duration represents the time it took for the ultrasonic waves to travel to the obstacle and back. We then calculate the distance using the formula distance = duration * 0.0343 / 2, where 0.0343 is the speed of sound in cm/μs and we divide by 2 because the waves travel to the obstacle and back.

Finally, we print the calculated distance to the Serial Monitor and add a 500-millisecond delay before the next measurement.

Tips

  1. Accurate High - Duration Measurement:

When using the pulseIn() function, it's important to note that it measures the duration of a pulse. In the case of the HC-SR04, this is the time the Echo pin is high. To ensure accurate measurements, make sure there are no other electrical interferences that could affect the pulse duration. Also, be aware that if the obstacle is too far away, the pulse may time out. You can set a timeout value in the pulseIn() function to handle such cases gracefully. For example, long duration = pulseIn(echoPin, HIGH, 20000); where 20000 is the timeout value in microseconds.

  1. Avoiding Noise Sources:

Ultrasonic waves can be affected by loud noise sources. When placing the HC – SR04 in your project, avoid areas with high – intensity sound, such as near speakers or in a very noisy industrial environment. Noise can interfere with the ultrasonic waves emitted by the sensor, leading to inaccurate distance measurements. If you must use the sensor in a noisy area, consider using sound – absorbing materials or enclosures to shield the sensor from the noise.

Raspberry Pi Integration

Voltage Caution

One of the key considerations when integrating the HC – SR04 with a Raspberry Pi is the voltage levels. The GPIO (General – Purpose Input/Output) pins on a Raspberry Pi can only accept a maximum voltage of 3.3V. However, the HC – SR04 operates on 5V, and the Echo pin of the HC – SR04 may output a 5V signal. Connecting a 5V signal directly to a Raspberry Pi GPIO pin can damage the Pi.

To solve this issue, you can use a voltage divider circuit. A simple voltage divider using a 1kΩ and a 2kΩ resistor can be used to convert the 5V output from the Echo pin of the HC-SR04 to a 3.3V-compatible signal for the Raspberry Pi. The formula for calculating the output voltage V out of a voltage divider is V out = V in × R 2 R 1 + R 2 , where V in is the input voltage (5V in this case), R 1 is the first resistor (1kΩ), and R 2 is the second resistor (2kΩ). Plugging in the values, we get V out = 5 × 2000 1000 + 2000 3.33 V , which is within the safe range for the Raspberry Pi GPIO pin.

Wiring

  • VCC: Connect the VCC pin of the HC – SR04 to the 5V pin on the Raspberry Pi. This powers up the HC – SR04 sensor module.

  • GND: The GND pin of the HC – SR04 should be connected to the GND pin on the Raspberry Pi to establish a common ground.
  • Trig: Connect the Trig pin of the HC – SR04 to GPIO 17 on the Raspberry Pi. The Raspberry Pi will use this pin to send the 10μs high – level trigger pulse to the HC – SR04.
  • Echo: The Echo pin of the HC – SR04, after passing through the voltage divider circuit (1kΩ and 2kΩ resistors), is connected to GPIO 27 on the Raspberry Pi. The Raspberry Pi will read the high – duration pulse on this pin to calculate the distance.
The wiring can be summarized as follows:
				
					       HC - SR04         Raspberry Pi
         VCC ------------ 5V
         GND ------------ GND
         Trig ------------ GPIO 17
         Echo (through voltage divider) ------------ GPIO 27
				
			

Python Code

Here is a Python code example using the RPi.GPIO library to interface the HC – SR04 with a Raspberry Pi:
				
					import RPi.GPIO as GPIO
import time

# Set the GPIO mode
GPIO.setmode(GPIO.BCM)

# Define the pins
TRIG = 17
ECHO = 27

# Set up the pins
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

def measure_distance():
    # Send a 10μs high - level pulse to trigger the sensor
    GPIO.output(TRIG, True)
    time.sleep(0.00001)
    GPIO.output(TRIG, False)

    # Wait for the echo to start
    while GPIO.input(ECHO)==0:
        pulse_start = time.time()

    # Wait for the echo to end
    while GPIO.input(ECHO)==1:
        pulse_end = time.time()

    pulse_duration = pulse_end - pulse_start
    distance = pulse_duration * 17150  # Speed of sound in cm/s divided by 2
    distance = round(distance, 2)

    return distance

try:
    while True:
        dist = measure_distance()
        print(f"Distance: {dist} cm")
        time.sleep(1)

except KeyboardInterrupt:
    print("Measurement stopped by User")
    GPIO.cleanup()

				
			

In this code, we first import the necessary libraries, RPi.GPIO for controlling the GPIO pins on the Raspberry Pi and time for adding delays. We then set the GPIO mode to BCM (Broadcom SOC channel numbering). We define the TRIG and ECHO pins and set up the TRIG pin as an output and the ECHO pin as an input.

The measure_distance function is where the magic happens. It sends a 10μs high - level pulse to the TRIG pin to trigger the HC - SR04. Then, it waits for the ECHO pin to go high (indicating the start of the echo) and records the start time. It then waits for the ECHO pin to go low (indicating the end of the echo) and records the end time. The time difference between the start and end times is used to calculate the distance. The distance is calculated by multiplying the pulse duration by the speed of sound in cm/s (34300 cm/s) and dividing by 2 (since the sound travels to the obstacle and back).

In the try block, we continuously measure the distance and print it to the console every second. If the user presses Ctrl + C (KeyboardInterrupt), the program cleans up the GPIO pins and exits gracefully.

ESP32 Configuration

Pin Assignment

The ESP32 is a powerful microcontroller with multiple GPIO (General – Purpose Input/Output) pins. When connecting the HC – SR04 to an ESP32, you can use the 5V from the ESP32’s VOUT pin to power the HC – SR04. For the Trig and Echo pins, you can connect them to any available GPIO pins. For example, you can connect the Trig pin to GPIO 14 and the Echo pin to GPIO 15. However, make sure to choose pins that are not already in use by other components in your project.

Arduino IDE Code

The code for using the HC – SR04 with an ESP32 in the Arduino IDE is quite similar to the Arduino code. Here is an example:
				
					const int trigPin = 14;
const int echoPin = 15;

void setup() {
  Serial.begin(115200);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

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

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(500);
}

				
			

In the setup function, we initialize the serial communication at a baud rate of 115200. We then set the trigPin as an output pin and the echoPin as an input pin.

In the loop function, the process of triggering the HC - SR04 and measuring the distance is the same as in the Arduino code. We send a 10μs high - level pulse to the trigPin to trigger the sensor, measure the duration of the high - level pulse on the echoPin using pulseIn , and calculate the distance.

However, when using the ESP32 in the Arduino IDE, make sure to select the correct ESP32 board in the IDE. Also, if you plan to integrate the ESP32 with IoT (Internet of Things) features such as WiFi or Bluetooth, you need to handle the initialization of these features in your code. For example, if you want to send the distance data over WiFi, you would need to add code to connect to a WiFi network and set up a server or client to send the data.

Creative Project Ideas Using HC-SR04

Obstacle-Avoiding Robot

The obstacle – avoiding robot is a fascinating and practical application of the HC – SR04 ultrasonic sensor module. Its primary function is to navigate through its environment safely by detecting obstacles in its path. This is achieved by using multiple HC – SR04 sensors strategically placed on the robot.

The sensors are configured to detect obstacles from different directions. For example, a set of sensors is placed at the front of the robot to detect any obstacles directly in its forward – moving path. Additionally, sensors are placed on the sides of the robot to detect obstacles that may be approaching from the sides. When an obstacle is detected, the robot’s control system, which is often based on a microcontroller like Arduino, calculates the distance to the obstacle using the data from the HC – SR04 sensors.

Based on this distance information, the control system then determines the appropriate action to take to avoid the obstacle. This usually involves steering the motors in a way that changes the robot’s direction. For instance, if an obstacle is detected on the left – hand side of the robot, the control system may instruct the left – hand motor to slow down or reverse while the right – hand motor continues to run at a normal speed. This causes the robot to turn to the right, away from the obstacle.

To build this project, you will need several key components. An Arduino serves as the brain of the operation. It processes the data received from the HC – SR04 sensors and sends commands to the motors. Motors are required to drive the wheels of the robot, enabling it to move. A motor driver, such as the L298N, is essential for controlling the motors. The L298N can handle the relatively high – current requirements of the motors and allows the Arduino to control the speed and direction of the motors effectively. And of course, multiple HC – SR04 sensors are needed for front and side detection. By combining these components and writing the appropriate code to control them, you can create a fully functional obstacle – avoiding robot.

Smart Trash Can

The smart trash can is a great example of how the HC – SR04 ultrasonic sensor module can be used to enhance the functionality of everyday objects. In this application, the smart trash can is designed to have an auto – open lid feature. This feature is triggered by the presence of a person approaching the trash can.

The HC – SR04 sensor is mounted on the trash can in such a way that it can detect the distance to any objects in front of it. When someone approaches the trash can, the sensor measures the distance between the trash can and the person. If the measured distance falls below a pre – set threshold (for example, 20 cm), it indicates that a person is close enough to the trash can to need to use it. At this point, the sensor sends a signal to a servo motor.

The servo motor is connected to the lid of the trash can and is responsible for opening and closing it. When it receives the signal from the HC – SR04 sensor, the servo motor rotates to open the lid. This hands – free operation is not only convenient for the user but also helps to keep the trash can clean and hygienic as there is no need to touch the lid directly.

When writing the code for this project, setting the distance threshold is a crucial step. You need to carefully calibrate this value based on the specific requirements of your smart trash can. If the threshold is set too high, the lid may open unnecessarily when someone is still some distance away from the trash can. On the other hand, if the threshold is set too low, the lid may not open in time when the user approaches. A well – calibrated distance threshold ensures that the smart trash can functions optimally.

Water Level Monitor

The water level monitor is a practical application of the HC – SR04 ultrasonic sensor module, especially in situations where it is necessary to keep track of the water level in a tank. This could be in a household water storage tank, an industrial water – holding tank, or even an aquarium.

The HC – SR04 sensor is installed above the water tank. It emits ultrasonic waves downwards towards the water surface. These waves travel through the air and bounce back when they hit the water surface. The sensor then measures the time it takes for the waves to travel to the water surface and back. Using the known speed of sound in air, the distance from the sensor to the water surface can be calculated.

In many cases, the water level monitor is integrated with an IoT (Internet of Things) system. For example, it can be connected to a Blynk app. The calculated water level data is sent to the app, allowing users to monitor the water level remotely. This is especially useful for industrial applications where real – time monitoring of water levels is crucial for the proper functioning of processes.

One important aspect to consider when setting up a water level monitor is calibration. Since the sensor is installed at a certain height above the base of the tank, this height needs to be accounted for in the distance calculations. For example, if the sensor is installed 50 cm above the base of the tank, and the calculated distance from the sensor to the water surface is 30 cm, then the actual water level in the tank is 20 cm. By accurately calibrating the sensor height and performing the necessary calculations, you can ensure that the water level monitor provides accurate and reliable readings.

Troubleshooting Common Issues

Inconsistent Readings

One of the most common issues users encounter with the HC – SR04 ultrasonic sensor module is inconsistent readings. This can be quite frustrating, especially when you’re relying on accurate distance measurements for your project.

Cause: Multi - path reflections or unstable power

Multi – path reflections occur when the ultrasonic waves emitted by the sensor bounce off multiple surfaces before reaching the receiver. This can happen in complex environments with lots of objects or in areas with large, reflective surfaces. For example, in a room with many pieces of furniture and mirrors, the ultrasonic waves may bounce off the furniture, walls, and mirrors before being detected by the receiver. This makes it difficult for the sensor to accurately calculate the distance to the intended object, resulting in inconsistent readings.

Unstable power is another culprit. If the power supply to the HC – SR04 is not stable, it can cause the sensor to malfunction. Voltage fluctuations can affect the proper functioning of the ultrasonic transmitter and receiver, leading to erratic distance measurements. For instance, if you’re using a battery that is running low or a power adapter with poor voltage regulation, the sensor may not receive a consistent 5V power supply, which can impact its performance.

Fix: Add a protective casing for the sensor and use a regulated 5V power source

Adding a protective casing around the sensor can help reduce the impact of multi – path reflections. The casing can be designed to direct the ultrasonic waves in a more focused manner, reducing the chances of the waves bouncing off unwanted surfaces. A simple cardboard or plastic casing with a narrow opening in the front can be effective in this regard.

Using a regulated 5V power source is crucial for stable operation. A power supply with built – in voltage regulation, such as a high – quality wall adapter or a voltage – regulated power module, ensures that the HC – SR04 receives a consistent 5V. This helps to eliminate any issues caused by voltage fluctuations and improves the overall accuracy and consistency of the sensor’s readings.

No Output Signal

Another common problem is when the HC – SR04 fails to produce an output signal. This can be a sign of a few different issues, and it’s important to systematically check each possibility to get the sensor working again.
Check: Verify wiring (especially VCC/GND), voltage divider for Raspberry Pi, and code logic for trigger/echo timing
First and foremost, carefully verify the wiring. Ensure that the VCC and GND pins are correctly connected to the power source and ground, respectively. A loose or incorrect connection can prevent the sensor from powering up properly or can cause electrical shorts that disrupt the normal operation of the module. In many cases, a simple visual inspection and re – connection of the wires can solve the problem.

If you’re using the HC – SR04 with a Raspberry Pi, don’t forget to check the voltage divider circuit. As mentioned earlier, the Raspberry Pi’s GPIO pins can only handle 3.3V, and a voltage divider is often used to convert the 5V output from the Echo pin of the HC – SR04 to a 3.3V – compatible signal. If the voltage divider components (usually resistors) are damaged or incorrectly connected, it can result in no output signal being received by the Raspberry Pi.

The code logic for trigger/echo timing is also a critical area to check. Make sure that the code is sending the correct trigger signal (a 10μs high – level pulse) to the Trig pin and that it’s correctly measuring the duration of the high – level pulse on the Echo pin. Incorrect code can prevent the sensor from being triggered or can cause the microcontroller to misinterpret the echo signal, leading to no output or incorrect distance calculations. For example, if the delay times in the code are set incorrectly, it can disrupt the proper sequence of triggering the sensor and reading the echo.

Out - of - Range Errors

Out – of – range errors can occur when the object being detected is either too close or too far from the HC – SR04 sensor. This can cause issues in your project, especially if your code is not properly equipped to handle such situations.
Solution: Implement a timeout (e.g., 38ms for no echo) and handle 0 or ∞ values gracefully in code
Implementing a timeout in your code is a useful way to handle cases where the object is too far away for the sensor to detect an echo within a reasonable time. For example, if no echo is received within 38ms, it’s a good indication that the object is beyond the sensor’s range. In your code, you can set up a timer that starts when the trigger signal is sent and stops when an echo is received. If the timer reaches the timeout value without receiving an echo, you can assume that the object is out of range and take appropriate action, such as displaying an error message or setting a default distance value.

Handling 0 or ∞ (infinity) values gracefully in code is also important. A distance value of 0 may indicate that the sensor is too close to an object, closer than its minimum detectable range. In such cases, you may want to set a minimum distance threshold in your code and adjust the distance value accordingly. Similarly, if the code calculates a distance value that is extremely large (approaching infinity), it’s likely an indication of an error, such as a problem with the echo detection or incorrect calculations. Your code should be able to handle these cases gracefully, for example, by logging an error message or attempting to re – measure the distance.

HC-SR04 vs. Other Distance Sensors

vs. Infrared Sensors

Table 1: HC-SR04 (Ultrasonic) vs Infrared Sensors

HC-SR04

Range: 2cm–400cm (Abstract 1, 6)

Accuracy: ±3mm (ideal conditions, Abstract 1)

Voltage: 5V (fixed, Abstract 1)

Pros: No light interference, longer range (Abstract 5)

Cons: Reduced near-range accuracy, ultrasonic noise sensitivity (Abstract 1)

Infrared

Range: Typically <100cm (Abstract 1, 5)

Accuracy: ±5mm–1cm (affected by color/material, Abstract 5)

Voltage: 3.3V–5V (flexible, Abstract 5)

Pros: Small size, low cost (Abstract 1)

Cons: Ambient light/color interference (Abstract 5)

The table 1 highlights the trade-off between HC-SR04’s robust long-range detection (2cm–400cm) and infrared sensors’ compact size/low cost, noting HC-SR04’s immunity to light interference vs. infrared’s vulnerability to ambient light and material color.

vs. Laser Sensors

Table 2: HC-SR04 vs Laser/ToF (VL53L0X)

HC-SR04

Range: 2cm–400cm (Abstract 1, 4)

Accuracy: ±3mm (Abstract 4)

Update Rate: 60ms (Abstract 4)

Cost: ~$2–3 (Abstract 1)

Weakness: 15° cone angle, environmental noise (Abstract 1)

Laser/ToF (VL53L0X)

Range: 5cm–200cm (Abstract 1, 3)

Accuracy: ±1mm–3mm (Abstract 3)

Update Rate: 20ms (faster, Abstract 4)

Cost: ~$10–15 (Abstract 1)

Strength: 5° narrow beam, interference-resistant (Abstract 3)

The table 2 compares HC-SR04’s cost-effectiveness ($2–3) and wide range (400cm) with Laser/ToF sensors’ superior precision (±1mm) and speed (20ms update rate), ideal for applications requiring high accuracy in controlled environments.

vs. US - 100 Module

Table 3: HC-SR04 vs US-100 (Ultrasonic)

HC-SR04

Range: 2cm–400cm (Abstract 2, 6)

Accuracy: ±3mm (nominal, Abstract 2)

Voltage: 5V only (Abstract 6)

Feature: GPIO-only, no temperature compensation (Abstract 3)

Issue: Random values beyond 400cm (Abstract 6)

US-100

Range: 2cm–450cm (Abstract 2, 3)

Accuracy: ±2mm (better in tests, Abstract 3)

Voltage: 3.3V–5V (Abstract 3)

Feature: Temperature compensation (UART mode), error codes (Abstract 6)

Downside: Higher cost ($5–8), UART setup required (Abstract 3)

The table 3 showcases US-100’s enhanced range (450cm), better accuracy (±2mm), and 3.3V/5V compatibility against HC-SR04’s simplicity (GPIO-only), highlighting US-100’s temperature compensation feature for industrial use at a higher cost ($5–8).

Advanced Techniques and Optimizations

Multi-Sensor Calibration

For more complex applications, especially in scenarios where a 360° view is essential, using multiple HC – SR04 sensors can be a game – changer. In a robotic application, for example, having multiple HC – SR04 sensors strategically placed around the robot’s body can enable it to detect obstacles from all directions, providing a comprehensive view of its surroundings.

However, when using multiple sensors, cross – talk interference can become a significant issue. Cross – talk occurs when the ultrasonic waves emitted by one sensor interfere with the operation of another sensor. This can lead to inaccurate readings as the sensors may misinterpret the interfering waves as echoes from actual obstacles.

To mitigate cross – talk interference, several techniques can be employed. One approach is to time – multiplex the sensors. This involves activating the sensors one at a time, with sufficient time intervals between each activation. For example, if you have four HC – SR04 sensors on a robot, you can activate sensor 1, wait for it to complete its measurement cycle, then activate sensor 2, and so on. By doing this, you ensure that the ultrasonic waves from one sensor do not overlap with those of another sensor, reducing the chances of cross – talk.

Another technique is to use shielding materials. Placing a physical barrier, such as a thin sheet of metal or a sound – absorbing material, between the sensors can help block the ultrasonic waves from one sensor from reaching another. This can be especially useful in situations where the sensors are placed in close proximity to each other.

Calibration is also crucial when using multiple sensors. Each sensor may have slightly different characteristics, such as sensitivity or beam angle. By calibrating the sensors, you can account for these differences and ensure that the data from all sensors is consistent. This may involve measuring the distance to a known object with each sensor and adjusting the readings based on the differences.

Noise Filtering

In some environments, the readings from the HC – SR04 may be jittery, with small fluctuations in the measured distance that can be caused by various factors such as electrical noise, minor air currents, or interference from other nearby electronics. To address this issue, noise – filtering techniques can be applied.

One commonly used method is the moving average filter. The moving average filter works by calculating the average of a series of consecutive distance readings. For example, instead of using a single distance reading, you can take the last 5 readings and calculate their average. This smooths out the jittery readings, as the small fluctuations tend to cancel each other out when averaged. In Python, the implementation of a simple moving – average filter for the HC – SR04 distance readings could look like this:
				
					distance_readings = []
num_readings = 5

def moving_average_filter(new_distance):
    distance_readings.append(new_distance)
    if len(distance_readings) > num_readings:
        distance_readings.pop(0)
    return sum(distance_readings) / len(distance_readings)

				
			

Another effective filtering method is the median filter. The median filter replaces each distance reading with the median value of a set of consecutive readings. The median is less sensitive to extreme values or outliers compared to the mean. For example, if you have a set of 5 distance readings [20, 22, 18, 50, 21], the median value is 21. By using the median filter, the outlier value of 50 would not significantly affect the filtered result. In Arduino, the implementation of a median filter could be as follows:

				
					const int numReadings = 5;
int readings[numReadings];
int readIndex = 0;
int total = 0;
int averageDistance = 0;

void addReading(int newReading) {
  total = total - readings[readIndex];
  readings[readIndex] = newReading;
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  if (readIndex >= numReadings) {
    readIndex = 0;
  }
}

int getMedian() {
  int sortedReadings[numReadings];
  for (int i = 0; i < numReadings; i++) {
    sortedReadings[i] = readings[i];
  }
  for (int i = 0; i < numReadings - 1; i++) {
    for (int j = i + 1; j < numReadings; j++) {
      if (sortedReadings[i] > sortedReadings[j]) {
        int temp = sortedReadings[i];
        sortedReadings[i] = sortedReadings[j];
        sortedReadings[j] = temp;
      }
    }
  }
  return sortedReadings[numReadings / 2];
}

				
			

Custom Work Modes

Some of the newer versions of the HC – SR04 ultrasonic sensor module offer additional flexibility through custom work modes. These modes can be configured via resistor settings, allowing for different communication protocols and operational characteristics.
One such mode is the GPIO (General – Purpose Input/Output) mode, which is the standard mode for most basic applications. In this mode, the module operates as described in the earlier sections, with the Trig and Echo pins used for triggering the distance measurement and receiving the echo signal, respectively.

However, there are also UART (Universal Asynchronous Receiver/Transmitter) and I2C (Inter – Integrated Circuit) modes available on certain HC – SR04 versions. In UART mode, the module can communicate with a microcontroller using serial communication. This can be useful in applications where a more standardized serial communication protocol is preferred, such as in some industrial control systems or when integrating with devices that have built – in UART interfaces.

The I2C mode, on the other hand, enables communication over an I2C bus. This is beneficial in multi – device setups where multiple sensors or components need to communicate with a single microcontroller. The I2C bus allows for a more efficient use of the microcontroller’s pins, as multiple devices can share the same two – wire bus (SDA – Serial Data Line and SCL – Serial Clock Line).

To configure the module for these custom modes, you need to refer to the module’s documentation to determine the appropriate resistor values. For example, to enable UART mode, you may need to connect a specific resistor between two pins on the module. Once the resistors are correctly configured, the module can be programmed to communicate in the desired mode. This may involve writing different code in your microcontroller to handle the UART or I2C communication protocols. For instance, in a Raspberry Pi project using the I2C – configured HC – SR04, you would use the smbus library in Python to communicate with the sensor over the I2C bus.

Conclusion

The HC – SR04 ultrasonic sensor module remains a staple in electronics projects due to its affordability, ease of use, and versatility. By mastering its working principle, interfacing with popular microcontrollers, and exploring creative applications, you can unlock its full potential for everything from basic distance measurement to complex IoT systems. Got questions or project ideas? Share them to us by the floating form! 🛠️

Subscribe

Join our subscribers list to get monthly blog updates, technology news, case studies. We will never send spam, and you can unsubscribe at any time.

Scroll to Top

Instant Quote