This project introduces students to the use of an HC-SR04 ultrasonic distance sensor with an ESP32 microcontroller. By measuring the time it takes for ultrasonic waves to bounce back from an object, the ESP32 calculates the distance. This data is displayed on the serial monitor and can optionally be shown on an OLED screen or web interface.
ESP32 GPIO5 —> Trig (HC-SR04)
ESP32 GPIO18 <—+— 2kΩ — Echo (HC-SR04)
|
1kΩ
|
GND
VCC → 5V
GND → GND
from machine import Pin, time_pulse_us
from time import sleep
# Pin configuration
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
# Function to get distance
def get_distance():
trig.off()
sleep(0.002)
trig.on()
sleep(0.00001)
trig.off()
duration = time_pulse_us(echo, 1, 30000) # timeout after 30ms
distance = (duration * 0.0343) / 2 # cm
return round(distance, 2)
# Main loop
while True:
d = get_distance()
print("Distance:", d, "cm")
sleep(1)
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.
You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.