Great idea — adding a buzzer makes your project feel like a real alarm system 🔥
Let’s upgrade your setup 👇
---
🔊 Add a Buzzer to Your ESP32 Smart Alert System
🧩 What changes?
Now your system will:
🚶 Detect motion
📏 Measure distance
🚨 Turn ON LED and 🔊 sound buzzer when object is too close
---
🔌 Buzzer Wiring
Simple Active Buzzer (recommended)
+ (VCC) → GPIO 15 (or any free pin)
– (GND) → GND
👉 If it’s a module, connect:
VCC → GPIO
GND → GND
---
💻 Updated MicroPython Code (with buzzer)
from machine import Pin, I2C, time_pulse_us
import time
from i2c_lcd import I2cLcd
# --- PIN SETUP ---
pir = Pin(13, [Link])
trig = Pin(5, [Link])
echo = Pin(18, [Link])
led = Pin(2, [Link])
buzzer = Pin(15, [Link]) # NEW
# --- LCD SETUP ---
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
def get_distance():
[Link]()
time.sleep_us(2)
[Link]()
time.sleep_us(10)
[Link]()
duration = time_pulse_us(echo, 1, 30000)
if duration < 0:
return -1
distance = (duration * 0.0343) / 2
return int(distance)
while True:
motion = [Link]()
if motion == 1:
distance = get_distance()
[Link]()
[Link]("Motion Detected\n")
if distance != -1:
[Link]("Dist: {} cm".format(distance))
else:
[Link]("Out of range")
# ALERT CONDITION
if distance != -1 and distance < 30:
[Link]()
[Link]() # 🔊 SOUND ON
else:
[Link]()
[Link]() # 🔇 SOUND OFF
else:
[Link]()
[Link]("No Motion")
[Link]()
[Link]()
[Link](0.5)
---
🔊 Optional: Make the Buzzer Beep Instead of Constant Sound
Replace this part:
[Link]()
With this:
for _ in range(3):
[Link]()
[Link](0.2)
[Link]()
[Link](0.2)
👉 This creates a beep-beep-beep alarm instead of a continuous tone.
---
⚠️Important Tips
✅ Works best with active buzzer (makes sound automatically)
⚠️Passive buzzer needs PWM (tell me if that’s what you have)
🔋 Don’t power buzzer directly from 5V GPIO
---
🔥 What you’ve built now
You officially have a:
🚨 Motion-triggered alarm system
📏 With distance-based warning
🔊 With sound + light alert
---
If you want next level, I can help you:
Make it send alerts to your phone 📱
Add a password keypad 🔐
Turn it into a full home security system
Just tell me 👍