深夜提醒

现在是深夜,建议您注意休息,不要熬夜哦~

🏮 🏮 🏮

新年快乐

祝君万事如意心想事成!

share-image
中
ESC

Connecting an HC-SR04 Ultrasonic Ranging Module and Buzzer Alarm to the ESP32

English 阅读中文版

Recently I connected an HC-SR04 ultrasonic ranging module to an ESP32, plus an active buzzer, and ran a small “alarm when the distance drops below 10 cm” experiment. Here’s a record of the wiring, the code, and the pitfalls I hit.

Experiment Goals

  • Use the ESP32 to read the distance measured by the HC-SR04 ultrasonic module.
  • When the distance is less than 10 cm, the buzzer beeps once every 3 seconds, for 200 ms each time.
  • When the distance is 10 cm or more, the buzzer stays quiet.

What You Need

Component Qty Notes
ESP32 development board 1 Any ordinary DevKit works
HC-SR04 ultrasonic module 1 Ranging distance 2 cm ~ 400 cm
Active buzzer module 1 Commonly low-level triggered
Jumper wires Several Female-to-female or male-to-female

Wiring

HC-SR04 to ESP32

HC-SR04 ESP32
VCC 3.3V or 5V
GND GND
Trig GPIO18 (D18)
Echo GPIO19 (D19)

The HC-SR04’s Echo outputs a 5V high level, while ESP32 GPIOs tolerate 3.3V. In my tests it worked when connected directly, but strictly speaking it’s safer to put a 1kΩ resistor between Echo and the ESP32 to divide the voltage.

Buzzer to ESP32

Buzzer ESP32
VCC 3.3V
GND GND
IO / SIG GPIO23 (D23)

Active buzzers come in two trigger types:

  • Low-level trigger: beeps when the GPIO outputs low, silent when high (the type used here).
  • High-level trigger: beeps when the GPIO outputs high, silent when low.

If the buzzer keeps sounding nonstop after wiring it up, you most likely set the trigger type backwards — just flip active_high in the code.

Actual wiring photos:

ESP32 与 HC-SR04 接线

ESP32 与蜂鸣器接线

Code

The project has two files: hcsr04.py is the ranging library, and main.py is the main program.

hcsr04.py

from machine import Pin
import time

TRIG_PIN = 5
ECHO_PIN = 4
MAX_ECHO_US = 30000
SOUND_SPEED_CM_PER_US = 0.0343


def measure_single(trig_pin=TRIG_PIN, echo_pin=ECHO_PIN):
trig = Pin(trig_pin, Pin.OUT)
echo = Pin(echo_pin, Pin.IN)

trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)

start_wait = time.ticks_us()
while echo.value() == 0:
if time.ticks_diff(time.ticks_us(), start_wait) > MAX_ECHO_US:
return -1

start = time.ticks_us()
while echo.value() == 1:
if time.ticks_diff(time.ticks_us(), start) > MAX_ECHO_US:
return -1

duration = time.ticks_diff(time.ticks_us(), start)
distance = duration * SOUND_SPEED_CM_PER_US / 2
return distance


def measure(samples=5, trig_pin=TRIG_PIN, echo_pin=ECHO_PIN):
values = []
for _ in range(samples):
d = measure_single(trig_pin, echo_pin)
if d >= 0:
values.append(d)
time.sleep_ms(10)

if not values:
return -1

values.sort()
n = len(values)
if n % 2 == 1:
return values[n // 2]
return (values[n // 2 - 1] + values[n // 2]) / 2

measure() takes 5 samples by default and returns the median, filtering out some glitches.

main.py

import time
from machine import Pin
from hcsr04 import measure

TRIG_PIN = 18
ECHO_PIN = 19
BUZZER_PIN = 23

# 低电平触发设为 False;高电平触发设为 True
active_high = False

buzzer = Pin(BUZZER_PIN, Pin.OUT)
buzzer.value(0 if active_high else 1)

THRESHOLD_CM = 10
INTERVAL_MS = 3000
BEEP_MS = 200

while True:
distance = measure(samples=5, trig_pin=TRIG_PIN, echo_pin=ECHO_PIN)
print('distance: %.1f cm' % distance)

if 0 <= distance < THRESHOLD_CM:
print('ALARM: distance < %d cm' % THRESHOLD_CM)
buzzer.value(1 if active_high else 0)
time.sleep_ms(BEEP_MS)
buzzer.value(0 if active_high else 1)

time.sleep_ms(INTERVAL_MS)

Core logic:

  • TRIG_PIN = 18 and ECHO_PIN = 19 correspond to D18 and D19.
  • Measure the distance once every 3 seconds.
  • When the distance is under 10 cm, the buzzer sounds for 200 ms.
  • active_high controls the buzzer’s trigger polarity.

Flashing and Uploading

This experiment uses MicroPython, so first flash the MicroPython firmware onto the ESP32, then upload the Python files.

1. Flash the MicroPython firmware

# 擦除 Flash
esptool --port /dev/ttyUSB0 erase_flash

# 写入固件(以 ESP32_GENERIC 为例)
esptool --port /dev/ttyUSB0 --baud 460800 write_flash 0x1000 ESP32_GENERIC-xxxxxx-vx.xx.x.bin

2. Upload the Python files

mpremote connect /dev/ttyUSB0 cp main.py :main.py
mpremote connect /dev/ttyUSB0 cp hcsr04.py :hcsr04.py
mpremote connect /dev/ttyUSB0 reset

3. Watch the serial output

mpremote connect /dev/ttyUSB0 repl

Normally you’ll see output like:

distance: 59.1 cm
distance: 59.0 cm
ALARM: distance < 10 cm
distance: 8.5 cm

Press Ctrl+] to exit the REPL.

Measured Results

  • With no obstacle, the serial port prints the distance every 3 seconds and the buzzer stays quiet.
  • Bringing my hand close to the ultrasonic module, once the distance drops below 10 cm the buzzer starts going “beep — beep —“ once every 3 seconds.
  • Move the hand away, and the buzzer stops.

Demo video:

Pitfall Log

  1. Buzzer won’t stop sounding

    • Cause: active_high didn’t match the buzzer’s actual trigger type.
    • Fix: set False for low-level trigger, True for high-level trigger.
  2. mpremote can’t enter Raw REPL

    • Cause: old firmware/abnormal program state, or the board is unresponsive inside a loop.
    • Fix: erase the Flash again and reflash the MicroPython firmware.
  3. Distance occasionally jumps

    • Cause: ultrasonic echoes are disturbed by the environment.
    • Fix: use measure() to sample multiple times and take the median — already built into the code.

Summary

This experiment was fairly simple overall; the main point was getting familiar with the ESP32 + MicroPython + HC-SR04 workflow. With the buzzer as the alarm output plus a threshold check, you get a practical proximity reminder device. It can later be extended into scenarios like reverse-parking radar, liquid-level alarms, or human-approach reminders.

文章作者:阿文
文章链接: https://www.awen.me/post/8158af42.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿文的博客!

评论

0 条评论
😀😃😄 😁😅😂 🤣😊😇 🙂🙃😉 😌😍🥰 😘😗😙 😚😋😛 😝😜🤪 🤨🧐🤓 😎🥸🤩 🥳😏😒 😞😔😟 😕🙁☹️ 😣😖😫 😩🥺😢 😭😤😠 😡🤬🤯 😳🥵🥶 😱😨😰 😥😓🤗 🤔🤭🤫 🤥😶😐 😑😬🙄 😯😦😧 😮😲🥱 😴🤤😪 😵🤐🥴 🤢🤮🤧 😷🤒🤕 🤑🤠😈 👿👹👺 🤡💩👻 💀☠️👽 👾🤖🎃 😺😸😹 😻😼😽 🙀😿😾 👍👎👏 🙌👐🤲 🤝🤜🤛 ✌️🤞🤟 🤘👌🤏 👈👉👆 👇☝️✋ 🤚🖐️🖖 👋🤙💪 🦾🖕✍️ 🙏💅🤳 💯💢💥 💫💦💨 🕳️💣💬 👁️‍🗨️🗨️🗯️ 💭💤❤️ 🧡💛💚 💙💜🖤 🤍🤎💔 ❣️💕💞 💓💗💖 💘💝💟 ☮️✝️☪️ 🕉️☸️✡️ 🔯🕎☯️ ☦️🛐⛎ ♈♉♊ ♋♌♍ ♎♏♐ ♑♒♓ 🆔⚛️🉑 ☢️☣️📴 📳🈶🈚 🈸🈺🈷️ ✴️🆚💮 🉐㊙️㊗️ 🈴🈵🈹 🈲🅰️🅱️ 🆎🆑🅾️ 🆘❌⭕ 🛑⛔📛 🚫💯💢 ♨️🚷🚯 🚳🚱🔞 📵🚭❗ ❕❓❔ ‼️⁉️🔅 🔆〽️⚠️ 🚸🔱⚜️ 🔰♻️✅ 🈯💹❇️ ✳️❎🌐 💠Ⓜ️🌀 💤🏧🚾 ♿🅿️🈳 🈂🛂🛃 🛄🛅🛗 🚀🛸🚁 🚉🚆🚅 ✈️🛫🛬 🛩️💺🛰️
加载中...

留言反馈

😀😃😄 😁😅😂 🤣😊😇 🙂🙃😉 😌😍🥰 😘😗😙 😚😋😛 😝😜🤪 🤨🧐🤓 😎🥸🤩 🥳😏😒 😞😔😟 😕🙁☹️ 😣😖😫 😩🥺😢 😭😤😠 😡🤬🤯 😳🥵🥶 😱😨😰 😥😓🤗 🤔🤭🤫 🤥😶😐 😑😬🙄 😯😦😧 😮😲🥱 😴🤤😪 😵🤐🥴 🤢🤮🤧 😷🤒🤕 🤑🤠😈 👿👹👺 🤡💩👻 💀☠️👽 👾🤖🎃 😺😸😹 😻😼😽 🙀😿😾 👍👎👏 🙌👐🤲 🤝🤜🤛 ✌️🤞🤟 🤘👌🤏 👈👉👆 👇☝️✋ 🤚🖐️🖖 👋🤙💪 🦾🖕✍️ 🙏💅🤳 💯💢💥 💫💦💨 🕳️💣💬 👁️‍🗨️🗨️🗯️ 💭💤❤️ 🧡💛💚 💙💜🖤 🤍🤎💔 ❣️💕💞 💓💗💖 💘💝💟 ☮️✝️☪️ 🕉️☸️✡️ 🔯🕎☯️ ☦️🛐⛎ ♈♉♊ ♋♌♍ ♎♏♐ ♑♒♓ 🆔⚛️🉑 ☢️☣️📴 📳🈶🈚 🈸🈺🈷️ ✴️🆚💮 🉐㊙️㊗️ 🈴🈵🈹 🈲🅰️🅱️ 🆎🆑🅾️ 🆘❌⭕ 🛑⛔📛 🚫💯💢 ♨️🚷🚯 🚳🚱🔞 📵🚭❗ ❕❓❔ ‼️⁉️🔅 🔆〽️⚠️ 🚸🔱⚜️ 🔰♻️✅ 🈯💹❇️ ✳️❎🌐 💠Ⓜ️🌀 💤🏧🚾 ♿🅿️🈳 🈂🛂🛃 🛄🛅🛗 🚀🛸🚁 🚉🚆🚅 ✈️🛫🛬 🛩️💺🛰️