from machine import Pin, ADC, PWM
import time
# PIR sensor (pokret)
pir = Pin(15, Pin.IN)
# Ultrazvuk
trig = Pin(14, Pin.OUT)
echo = Pin(13, Pin.IN)
# RGB LED (pretpostavljamo common cathode - spojen com na GND)
red = Pin(10, Pin.OUT)
green = Pin(11, Pin.OUT)
blue = Pin(12, Pin.OUT)
# Buzzer (PWM za zvuk)
buzzer = PWM(Pin(9))
# Taster (reset alarma)
button = Pin(8, Pin.IN, Pin.PULL_UP)
# Potenciometar
pot = ADC(Pin(26))
# Funkcija za merjenje rastojanja
def measure_distance():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
start = time.ticks_us()
timeout = 30000 # 30ms timeout (~5m udaljenost)
while echo.value() == 0:
if time.ticks_diff(time.ticks_us(), start) > timeout:
return 999 # previše daleko ili nema objekta
start = time.ticks_us()
while echo.value() == 1:
if time.ticks_diff(time.ticks_us(), start) > timeout:
return 999
duration = time.ticks_diff(time.ticks_us(), start)
distance = (duration / 2) / 29.1
return distance
# Funkcija za paljenje RGB LED
def set_rgb(r, g, b):
red.value(not r) # invertuj logiku
green.value(not g)
blue.value(not b)
# Alarm stanje
alarm_active = False
while True:
# Čitanje sa senzora
print("PIR:", pir.value())
motion = pir.value()
distance = measure_distance()
pot_value = pot.read_u16() # 0 - 65535
threshold_cm = pot_value / 65535 * 100 # skaliramo na 0 - 100 cm
set_rgb(1, 0, 0)
buzzer.freq(1000)
buzzer.duty_u16(30000)
time.sleep(1)
set_rgb(0, 1, 0)
buzzer.duty_u16(0)
time.sleep(1)
# Detekcija
if motion or distance < threshold_cm:
alarm_active = True
# Ako je alarm aktivan
if alarm_active:
set_rgb(1, 0, 0) # crveno
buzzer.freq(1000)
buzzer.duty_u16(30000)
else:
set_rgb(0, 1, 0) # zeleno
buzzer.duty_u16(0)
# Pritisnut taster?
if button.value() == 0:
alarm_active = False
set_rgb(0, 1, 0) # zeleno
buzzer.duty_u16(0)
time.sleep(0.1)