import dht
import utime
from machine import Pin, PWM, time_pulse_us
dht_sensor = dht.DHT22(Pin(10))
ldr = Pin(11, Pin.IN)
trig = Pin(7, Pin.OUT)
echo = Pin(5, Pin.IN)
led_r = Pin(16, Pin.OUT)
led_g = Pin(17, Pin.OUT)
led_b = Pin(18, Pin.OUT)
buzzer = PWM(Pin(15))
buzzer.duty_u16(0)
button = Pin(14, Pin.IN, Pin.PULL_DOWN)
TEMP_WARN = 28
TEMP_ALARM = 32
DIST_WARN = 15
DIST_ALARM = 8
DARK_STATE = 1
emergency = False
last_press = 0
DEBOUNCE = 250
def set_color(r, g, b):
led_r.value(r)
led_g.value(g)
led_b.value(b)
def green():
set_color(0,1,0)
def blue():
set_color(0,0,1)
def red():
set_color(1,0,0)
def off():
set_color(0,0,0)
def beep(freq=1500, t=100):
buzzer.freq(freq)
buzzer.duty_u16(30000)
utime.sleep_ms(t)
buzzer.duty_u16(0)
def read_dht():
try:
dht_sensor.measure()
return dht_sensor.temperature(), dht_sensor.humidity()
except:
return None, None
def read_distance():
trig.low()
utime.sleep_us(2)
trig.high()
utime.sleep_us(10)
trig.low()
try:
t = time_pulse_us(echo, 1, 30000)
if t < 0:
return None
return (t * 0.0343) / 2
except:
return None
def check_button():
global emergency, last_press
now = utime.ticks_ms()
if button.value() == 1:
if utime.ticks_diff(now, last_press) > DEBOUNCE:
emergency = not emergency
last_press = now
if emergency:
print("!АВАРИЙНАЯ ОСТАНОВКА!")
else:
print("Система снова включена")
while button.value() == 1:
utime.sleep_ms(10)
print("Система запущена")
while True:
check_button()
if emergency:
red()
beep(2000, 200)
utime.sleep_ms(200)
continue
temp, hum = read_dht()
dist = read_distance()
light = ldr.value()
print("\\")
print("Temp:", temp)
print("Hum:", hum)
print("Dist:", dist)
print("Light:", light)
if temp is None or dist is None:
print("Ошибка датчика")
blue()
beep(1000, 100)
utime.sleep(1)
continue
alarm = False
warn = False
if temp >= TEMP_ALARM:
alarm = True
elif temp >= TEMP_WARN:
warn = True
if dist <= DIST_ALARM:
alarm = True
elif dist <= DIST_WARN:
warn = True
if light == DARK_STATE:
warn = True
if alarm:
print("АВАРИЯ")
red()
beep(1800, 150)
elif warn:
print("ПРЕДУПРЕЖДЕНИЕ")
blue()
beep(1200, 80)
else:
print("НОРМА")
green()
utime.sleep(1)