MicroPython HC-SR04 distance with a driver file on an ESP32-DevKitC V4
MicroPython on an ESP32: a small sr04.py driver times the HC-SR04 echo with time_pulse_us() and prints the distance twice a second. The whole build, an ESP32-DevKitC V4 and 3 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Intermediate About 30 minutes to build and run. Runs in your browser. Free, and no account needed.
The parts retail for about $13.10. On Mokxi they're free.
What you'll learn
- Splitting code into a driver module and a main program
- Timing a pulse with
time_pulse_us - Converting echo time to distance
- A voltage divider protects a 3.3 V input
- A
Nonereturn value signals no reading
- Difficulty: Intermediate
- Time: About 30 minutes
- Board: ESP32-DevKitC V4
- Parts: 5
How it works
This MicroPython project splits the work into two files. The driver file sr04.py knows how to talk to the HC-SR04 ultrasonic ranger, and main.py only asks for a distance. TRIG is on GPIO 13 and ECHO on GPIO 14.
To measure, the driver sets TRIG high for 20 microseconds, then uses time_pulse_us to time how long ECHO stays high. Sound travels 0.0343 cm per microsecond, and the trip is there and back, so the distance is the time times 0.0343 divided by 2.
The sensor needs 5 V but the ESP32 pins take 3.3 V. A 1k and 2k resistor divider drops the ECHO signal to a safe level. The program prints the distance twice a second, or "Out of range" if no echo comes back.
Parts list
5 parts, plus the jumper wires. They retail for about $13.10; on Mokxi they're free.
- 1 × ESP32-DevKitC V4
- 1 × Ultrasonic rangerIn Halloween Prop Kit.
- 1 × Resistor, 1k ΩIn Starter Kit, Claw Machine Kit, Halloween Prop Kit.
- 1 × Resistor, 2k ΩIn Starter Kit, Claw Machine Kit, Halloween Prop Kit.
- 1 × Power, 5 V
Kits that can build it
These 3 starter kits have every part in the circuit. Each kit's page lists what else it can build.
Wiring table
Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.
| Part and pin | Connects to |
|---|---|
| Resistor, 1k Ω pin 2 | ESP32-DevKitC V4 pin 14 |
| Resistor, 2k Ω pin 1 | ESP32-DevKitC V4 pin 14 |
| Ultrasonic ranger pin TRIG | ESP32-DevKitC V4 pin 13 |
| Ultrasonic ranger pin VCC | 5 V |
| Resistor, 1k Ω pin 1 | Ultrasonic ranger pin ECHO |
| Ultrasonic ranger pin GND | Ground |
| Resistor, 2k Ω pin 2 | Ground |
The code
The MicroPython code exactly as the editor opens it. Change a line there and press Run: the board runs it on the official MicroPython firmware, with nothing to compile.
# Ultrasonic ranging with a driver: sr04.py (its own tab) does the
# pulse and the timing, so the program only asks for the distance.
from sr04 import SR04
import time
sensor = SR04(13, 14) # TRIG on GPIO 13, ECHO on GPIO 14
while True:
cm = sensor.distance_cm()
print("Distance: %.1f cm" % cm if cm is not None else "Out of range")
time.sleep_ms(500)
# sr04.py: an HC-SR04 ultrasonic sensor, timed with time_pulse_us().
from machine import Pin, time_pulse_us
import time
class SR04:
def __init__(self, trig, echo):
self.trig = Pin(trig, Pin.OUT, value=0)
self.echo = Pin(echo, Pin.IN)
def distance_cm(self):
self.trig.value(1)
time.sleep_us(20) # 10 us or more starts a ping
self.trig.value(0)
us = time_pulse_us(self.echo, 1, 30000) # how long ECHO is high
if us < 0:
return None # no echo: nothing in range
return us * 0.0343 / 2
Troubleshooting
The usual mistakes with this circuit, and the fix for each.
- It always says "Out of range" This project
Check that TRIG goes to GPIO 13 and the divided ECHO goes to GPIO 14, and the sensor has 5 V and ground. - The ESP32 gets hot or acts oddly This project
Do not wire ECHO straight to the pin. Use the 1k and 2k divider. - Distance reads zero, or never changes. Ultrasonic ranger
Power it from 5 V and share ground. Send a 10 microsecond HIGH pulse on TRIG, then time ECHO with pulseIn. Check TRIG and ECHO are not swapped. - Readings jump around or are wrong on a 3.3 V board. Ultrasonic ranger
ECHO outputs 5 V, so divide it down for 3.3 V boards. Aim at flat, hard surfaces. The range is about 2 cm to 4 m, and soft or angled targets bounce the sound away. - The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure. - A pull-up or pull-down resistor is missing, so the input floats and reads random values. Resistor
Tie the input to 5 V or ground through about 10k. Or use INPUT_PULLUP and wire the switch to ground. - The board is not found, or upload fails with a connecting message. ESP32-DevKitC V4
Use a USB cable that carries data, not charge only. Pick the ESP32 Dev Module board. If it still fails, hold BOOT while uploading starts, then release. - Some pins never read right, or the board will not boot with a wire attached. ESP32-DevKitC V4
GPIO34 to 39 are input only and have no pull-ups. GPIO6 to 11 run the flash, so leave them alone. GPIO0, 2 and 12 are boot pins; avoid pulling them the wrong way at reset.
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.