from machine import Pin, I2C
import ssd1306
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('Hello, Wokwi!', 10, 10)
oled.show()
from machine import Pin, I2C, Timer
import network
import time
from umqtt.robust import MQTTClient
import sys
import dht
import ssd1306
# Configuración de pines y dispositivos
i2c = I2C(0, scl=Pin(22), sda=Pin(21)) # Configuración de I2C
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c) # Inicialización de la pantalla OLED
sensor = dht.DHT22(Pin(19)) # Sensor DHT22 conectado al pin 19
# Definición de pines para los LEDs
led_yellow = Pin(5, Pin.OUT) # LED amarillo (D1)
led_blue = Pin(4, Pin.OUT) # LED azul (D2)
led_red = Pin(0, Pin.OUT) # LED rojo (D3)
# Configuración de conexión WiFi
print("Conectando a WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" ¡Conectado!")
# Configuración de conexión a Adafruit IO
ADAFRUIT_IO_URL = 'io.adafruit.com'
ADAFRUIT_USERNAME = 'hcarrascal12'
ADAFRUIT_IO_KEY = 'aio_ShFR06rySO6kkrB3bzZNHjGALcUF'
# IDs de los feeds en Adafruit IO
TOGGLE_FEED_ID = 'led'
TEMP_FEED_ID = 'temperature' # Cambiado a 'temperature' para reflejar la medición de temperatura
HUM_FEED_ID = 'humidity'
# Configuración de MQTT
mqtt_client_id = bytes('client_'+'12321', 'utf-8')
client = MQTTClient(client_id=mqtt_client_id, server=ADAFRUIT_IO_URL, user=ADAFRUIT_USERNAME, password=ADAFRUIT_IO_KEY, ssl=False)
# Función de callback para MQTT
def cb(topic, msg):
print('Datos recibidos: Tema = {}, Msg = {}'.format(topic, msg))
received_data = str(msg, 'utf-8')
if received_data == "0":
led_yellow.off() # Apaga el LED amarillo
led_blue.off() # Apaga el LED azul
led_red.on() # Enciende el LED rojo
elif received_data == "1":
led_yellow.off() # Apaga el LED amarillo
led_blue.on() # Enciende el LED azul
led_red.off() # Apaga el LED rojo
elif received_data == "2":
led_yellow.on() # Enciende el LED amarillo
led_blue.off() # Apaga el LED azul
led_red.off() # Apaga el LED rojo
# Formato de los feeds
temp_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, TEMP_FEED_ID), 'utf-8')
hum_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, HUM_FEED_ID), 'utf-8')
toggle_feed = bytes('{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, TOGGLE_FEED_ID), 'utf-8')
# Conexión MQTT y suscripción al feed del LED
try:
client.connect()
client.set_callback(cb)
client.subscribe(toggle_feed)
except Exception as e:
print('No se pudo conectar al servidor MQTT: {}{}'.format(type(e).__name__, e))
sys.exit()
# Función para medir temperatura y humedad, y controlar los LEDs correspondientes
def sens_data(data):
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
# Lógica para encender y apagar los LEDs correspondientes
if temp <= 24:
led_yellow.off() # Apaga el LED amarillo
led_blue.on() # Enciende el LED azul
led_red.off() # Apaga el LED rojo
elif temp > 24 and temp <= 30:
led_yellow.on() # Enciende el LED amarillo
led_blue.off() # Apaga el LED azul
led_red.off() # Apaga el LED rojo
else:
led_yellow.off() # Apaga el LED amarillo
led_blue.off() # Apaga el LED azul
led_red.on() # Enciende el LED rojo
# Publicar datos de temperatura y humedad en Adafruit IO
client.publish(temp_feed, bytes(str(temp), 'utf-8'), qos=0)
client.publish(hum_feed, bytes(str(hum), 'utf-8'), qos=0)
print("Temperatura: ", str(temp))
print("Humedad: ", str(hum))
oled.fill(0)
oled.text('Temp: ' + str(temp) + 'C', 10, 10)
oled.text('Hum: ' + str(hum) + '%', 10, 30)
oled.show()
# Configuración del temporizador para ejecutar sens_data cada 10 segundos
timer = Timer(0)
timer.init(period=10000, mode=Timer.PERIODIC, callback=sens_data)
# Bucle principal
while True:
try:
client.check_msg()
except:
client.disconnect()
sys.exit()