# -----------------------------------------------------------
# Smart Vehicle Security Demo (Wokwi / Raspberry Pi Pico)
# Components & Pins
# LED GP15 (active-high)
# Buzzer (+) GP13 (PWM audio)
# Push-button GP28 (active-low, internal pull-up)
# HC-SR04 Trig GP3
# HC-SR04 Echo GP2
# led anode pico gp15
# led cathode 330ohm resistor then pico gnd.1
# Button
# One leg on the left to pico GP28
# One leg on the right to pico GND.6
# HC-SR04 Trigger pico GP3
# HC-SR04 Echo pico GP2
# HC-SR04 VCC pico VBUS
# HC-SR04 GND pico GND.2
# Buzzer (+) pico GP13
# Buzzer (-) pico GND.3
# -----------------------------------------------------------
from machine import Pin, PWM, time_pulse_us
import utime
# ---------- I/O SETUP ----------
LED_PIN = 15
BUZZER_PIN = 13
BUTTON_PIN = 28
TRIG_PIN = 3
ECHO_PIN = 2
DIST_THRESHOLD_CM = 30 # Alarm when object is closer than this
led = Pin(LED_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
trigger = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
buzzer = PWM(Pin(BUZZER_PIN)) # PWM for sound
armed = True # System starts armed
# ---------- BUZZER HELPERS ----------
def sound_buzzer(duration=0.25, freq=1000, duty=20000):
"""Play a single tone."""
buzzer.freq(freq)
buzzer.duty_u16(duty) # 0–65535 (volume)
utime.sleep(duration)
buzzer.duty_u16(0) # Off
# ---------- DISTANCE MEASUREMENT ----------
def measure_distance():
"""Return distance in cm using HC-SR04."""
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(10)
trigger.low()
# Wait for echo and measure pulse
duration = time_pulse_us(echo, 1, 30000) # timeout 30 ms
if duration < 0: # -1/-2 = timeout
return 999
return duration * 0.0343 / 2 # Speed of sound
# ---------- ALARM ----------
def alarm(reason):
print("🚨 ALARM:", reason)
for i in range(5):
led.toggle()
sound_buzzer(freq=1500 if i % 2 else 900)
led.value(0)
# ---------- MAIN LOOP ----------
print("✅ System armed.")
last_button_state = 1
debounce_ms = 200
last_toggle_time = utime.ticks_ms()
while True:
# --- Button: arm / disarm ---
curr_state = button.value()
now = utime.ticks_ms()
if curr_state == 0 and last_button_state == 1 and utime.ticks_diff(now, last_toggle_time) > debounce_ms:
armed = not armed
state_txt = "🟢 Armed" if armed else "🔴 Disarmed"
print(state_txt)
sound_buzzer(duration=0.15, freq=600 if armed else 400)
last_toggle_time = now
last_button_state = curr_state
# --- Distance check (only if armed) ---
if armed:
dist = measure_distance()
if dist < DIST_THRESHOLD_CM:
alarm(f"Object at {dist:.1f} cm")
utime.sleep(0.4)