Processing math: 100%

Ultrasonic Distance Measurement HC-SR04

Distance measurement is vital in many applications like robotics, automation, and security systems. The HC-SR04 is a popular ultrasonic sensor used for non-contact distance measurements. This sensor operates by emitting an ultrasonic sound pulse and measuring the time it takes for the echo to return to calculate the distance to an object.

The HC-SR04 is reliable and accurate over short ranges, typically up to 4 meters. Use cases include parking sensors, obstacle avoidance in robotics, and interactive installations.

HC-SR04 Ultrasonic Distance Measurement Module

The HC-SR04 module includes an ultrasonic transmitter, a receiver, and a control circuit. It emits a high-frequency sound wave and receives the echo reflected from a target object. The distance is calculated based on the time interval between sending the wave and receiving the echo.

This module can be interfaced with microcontrollers (like Arduino or ESP32) using digital I/O pins. The HC-SR04 requires a short trigger pulse to start the measurement and then provides a pulse width output corresponding to the distance. The sensor requires a 5V power source.

The following is Micropython code to read 20 distance (cm) values over 10 seconds with the HC-SR04.

import time
from hcsr04 import HCSR04

sensor = HCSR04(trigger_pin=16, echo_pin=0)

for _ in range(20):
    print(f'Distance (mm): {sensor.distance_mm()}')
    time.sleep(0.5)

The hcsr04.py script is needed to interface with the HC-SR04 sensor. Thanks to Roberto Sánchez for the micropython-hcsr04 GitHub repository.

✅ Activity: Distance Measurement with HC-SR04

Here are a few applications where the HC-SR04 sensor might be useful:

  • Robotics: For detecting obstacles and aiding in navigation.
  • Home Automation: Such as turning lights on/off based on presence.
  • Security Systems: Detecting movement or presence in a particular area.
  • Educational Projects: To teach students about sensors and microcontrollers.

Experiment with the HC-SR04 sensor by measuring distances to various objects. Explore how the sensor accuracy varies with different materials and distances. Discuss the findings and the implications for potential applications.

Collect Data

Collect data using the following Python script, which takes 100 samples every 5 seconds. Position an object at a measured distance from the sensor, and move it as prompted, allowing a 5-second interval for repositioning. The data is stored in the dist_hcsr04.csv file on the microcontroller.

import time
from hcsr04 import HCSR04
from machine import Pin,SoftI2C

dist = HCSR04(trigger_pin=16, echo_pin=0)

fid = open('dist_hcsr04.csv','w')
fid.write('Time,Dist,Measured\n')
ts = time.time()

# calibration distances (inches)
for d in [35,20,10,30,15,5,25,0,35]:
   print(f'------Set distance to {d} inches---------')
   time.sleep(5)
   print('Reading 100 samples')
   for _ in range(100):
      fid.write(f'{time.time()-ts},{d},{dist.distance_mm()}\n')
      time.sleep(0.01)
fid.close()
print('done')

Compare the results of this test to the VL53L0X Laser Sensor. What are the advantages and disadvantages of using sound versus light to measure distance?

Solution

✅ Activity: Proximity Indicator

Create a proximity indicator with a Red (stop), Yellow (slow), Green (near), Blue (far) light LED. Use the HC-SR04 sensor to determine the distance of the approaching object.

  • Red: < 20 cm
  • Yellow: 20-50 cm
  • Green: 50-80 cm
  • Blue: >80 cm

Below is code to change the build-in color changing LED of the ESP32 S2 WROVER.

from machine import Pin
from neopixel import NeoPixel
from time import sleep

# Define the GPIO pin connected to the RGB LED
LED_PIN = 18  # Update this to the correct pin for your board

# Initialize the NeoPixel object
np = NeoPixel(Pin(LED_PIN), 1)  # '1' indicates a single LED

def set_color(r, g, b):
    """Set the color of the RGB LED."""
    np[0] = (r, g, b)
    np.write()

# Example usage: cycle through red, green, and blue colors
for i in range(2):
    set_color(255, 0, 0)  # Red
    sleep(1)
    set_color(255, 255, 0)  # Yellow
    sleep(1)
    set_color(0, 255, 0)  # Green
    sleep(1)
    set_color(0, 0, 255)  # Blue
    sleep(1)

Streaming Chatbot
💬