from machine import Pin, I2C, ADC, PWM
import dht
import ssd1306
import time
# ======================
# I2C OLED
# ======================
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# ======================
# DHT22
# ======================
sensor = dht.DHT22(Pin(4))
# ======================
# CO2 SIMULADO
# ======================
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB)
def co2_sim():
return 400 + (adc.read() * 1600 // 4095)
# ======================
# LEDS
# ======================
leds = {
"temp_g": Pin(14, Pin.OUT),
"temp_r": Pin(27, Pin.OUT),
"hum_g": Pin(26, Pin.OUT),
"hum_r": Pin(25, Pin.OUT),
"co2_g": Pin(33, Pin.OUT),
"co2_r": Pin(32, Pin.OUT),
}
# ======================
# BUZZER
# ======================
buzzer = PWM(Pin(13))
buzzer.freq(2000)
#Variable Rango óptimo
#Temperatura 18 – 25 °C
#Humedad 30 – 60 %
#CO₂ < 1000 ppm
# ======================
# FUNCIONES
# ======================
def set_led(ok, g, r):
leds[g].value(ok)
leds[r].value(not ok)
def beep():
buzzer.duty(512)
time.sleep(0.2)
buzzer.duty(0)
# ======================
# LOOP
# ======================
while True:
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
co2 = co2_sim()
# CONDICIONES
ok_t = 18 <= t <= 25
ok_h = 30 <= h <= 60
ok_c = co2 < 1000
# LEDS
set_led(ok_t, "temp_g", "temp_r")
set_led(ok_h, "hum_g", "hum_r")
set_led(ok_c, "co2_g", "co2_r")
alerta = not (ok_t and ok_h and ok_c)
# OLED
oled.fill(0)
oled.text("Temp: {:.1f}C".format(t), 0, 0)
oled.text("Hum: {:.1f}%".format(h), 0, 15)
oled.text("CO2: {}ppm".format(co2), 0, 30)
if alerta:
oled.text("ALERTA!", 0, 50)
beep()
oled.show()
time.sleep(2)