from machine import Pin, ADC, I2C
import dht
import time
# Configuración de pines
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=100000)
sensor_dht = dht.DHT22(Pin(4))
sensor_suelo = ADC(Pin(34))
bomba = Pin(5, Pin.OUT, value=1)
ventilador = Pin(18, Pin.OUT, value=1)
led = Pin(2, Pin.OUT, value=0)
# Configurar el sensor de suelo
sensor_suelo.atten(ADC.ATTN_11DB)
sensor_suelo.width(ADC.WIDTH_12BIT)
# Clase para la pantalla LCD
class LCD:
def __init__(self, i2c, direccion=0x27):
self.i2c = i2c
self.direccion = direccion
self.iniciar()
def iniciar(self):
comandos = [0x33, 0x32, 0x28, 0x0C, 0x06, 0x01]
for comando in comandos:
self.enviar(comando, 0)
def enviar(self, dato, rs):
# Primer nibble
valor = (dato & 0xF0) | 0x08 | rs
self.i2c.writeto(self.direccion, bytes([valor | 4, valor]))
# Segundo nibble
valor = ((dato << 4) & 0xF0) | 0x08 | rs
self.i2c.writeto(self.direccion, bytes([valor | 4, valor]))
def escribir(self, texto, x=0, y=0):
posicion = 0x80 | (0x40 * y + x)
self.enviar(posicion, 0)
for letra in texto:
self.enviar(ord(letra), 1)
# Intentar conectar la pantalla LCD
try:
lcd = LCD(i2c)
print("LCD conectada")
except:
lcd = None
print("LCD no encontrada")
print("Sistema iniciado...")
while True:
try:
# Leer sensores
sensor_dht.measure()
temperatura = sensor_dht.temperature()
humedad_suelo = int((sensor_suelo.read() / 4095) * 100)
# Decidir qué activar
bomba_on = humedad_suelo < 30
ventilador_on = temperatura > 28
# Controlar dispositivos
bomba.value(0 if bomba_on else 1) # 0 = ON, 1 = OFF
ventilador.value(0 if ventilador_on else 1)
led.value(1 if bomba_on or ventilador_on else 0)
# Crear texto para mostrar
linea1 = f"T:{temperatura:.1f}C H:{humedad_suelo}%"
linea2 = f"B:{'ON ' if bomba_on else 'OFF'} V:{'ON ' if ventilador_on else 'OFF'}"
print(f"{linea1} | {linea2}")
# Mostrar en LCD si está disponible
if lcd:
lcd.escribir(f"{linea1:<16}", 0, 0)
lcd.escribir(f"{linea2:<16}", 0, 1)
except Exception as error:
print(f"Error: {error}")
time.sleep(2)