from machine import Pin, ADC, time_pulse_us
import dht
import time
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
mq2 = ADC(Pin(12))
mq2.atten(ADC.ATTN_11DB)
pir = Pin(0, Pin.IN)
sensor = dht.DHT22(Pin(23))
led_dist = Pin(4, Pin.OUT)
led_gas = Pin(27, Pin.OUT)
led_pir = Pin(2, Pin.OUT)
led_temp = Pin(22, Pin.OUT)
DIST_MIN = 20
GAS_MAX = 2000
TEMP_MAX = 28
TIEMPO_PIR = 5000
lecturas_gas = []
temp = 0
hum = 0
hubo_mov = False
t_pir = 0
t_dht = 0
t_print = 0
def medir_distancia():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
duracion = time_pulse_us(echo, 1, 30000)
if duracion < 0:
return 999
distancia = (duracion / 2) / 29.1
return distancia
def promedio_gas():
lecturas_gas.append(mq2.read())
if len(lecturas_gas) > 5:
lecturas_gas.pop(0)
total = 0
for v in lecturas_gas:
total = total + v
return total / len(lecturas_gas)
def monitoreo():
global temp, hum, hubo_mov, t_pir, t_dht, t_print
ahora = time.ticks_ms()
d = medir_distancia()
if d < DIST_MIN:
led_dist.value(1)
else:
led_dist.value(0)
gas = promedio_gas()
if gas > GAS_MAX:
if (ahora // 100) % 2 == 0:
led_gas.value(1)
else:
led_gas.value(0)
else:
led_gas.value(0)
if pir.value() == 1:
hubo_mov = True
t_pir = ahora
if hubo_mov and time.ticks_diff(ahora, t_pir) < TIEMPO_PIR:
led_pir.value(1)
else:
led_pir.value(0)
hubo_mov = False
if time.ticks_diff(ahora, t_dht) >= 2000:
t_dht = ahora
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
except OSError as e:
print("Error de lectura DHT22")
if temp > TEMP_MAX:
if (ahora // 1000) % 2 == 0:
led_temp.value(1)
else:
led_temp.value(0)
else:
led_temp.value(0)
if time.ticks_diff(ahora, t_print) >= 1000:
t_print = ahora
print("Distancia:", d, "cm")
print("Gas:", gas)
print("Movimiento:", pir.value())
print("Temperatura:", temp, "°C", "Humedad:", hum, "%")
print("-----")
while True:
monitoreo()
time.sleep(0.05)