import network
import json
import dht
import time
from machine import Pin
from umqtt.simple import MQTTClient
# Configurações Wi-Fi e MQTT
SSID, PASS = "Wokwi-GUEST", "" # Note o "W" maiúsculo
BROKER = "broker.emqx.io"
PORT = 1883
TOPIC = b"pucpr/iot"
# Conexão Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASS)
print("Conectando ao Wi-Fi...")
for i in range(10):
if wlan.isconnected():
break
time.sleep(1)
print(".", end="")
if not wlan.isconnected():
print("\nFalha na conexão Wi-Fi")
print("Status:", wlan.status())
else:
print("\nConectado ao Wi-Fi!")
print("IP:", wlan.ifconfig()[0])
# Client ID mais simples para Wokwi
client_id = b"esp32_wokwi"
try:
print("Conectando ao broker MQTT...")
client = MQTTClient(client_id, BROKER, port=PORT, keepalive=30)
client.connect()
print("Conectado ao broker MQTT!")
except Exception as e:
print("Erro MQTT:", e)
print("Verifique se o broker está acessível no simulador")
# Continua execução mesmo sem MQTT para teste
client = None
# Hardware
sensor = dht.DHT22(Pin(2))
led = Pin(4, Pin.OUT)
LIMIAR = 28.0
def publicar_dados(t, u, estado_led):
if client is None:
print("MQTT não disponível - Simulando publicação")
return
try:
payload = {
"t": round(t, 1),
"u": round(u, 1),
"led": estado_led,
"timestamp": time.time()
}
client.publish(TOPIC, json.dumps(payload))
print("✓ Dados publicados:", payload)
except Exception as e:
print("Erro ao publicar:", e)
while True:
try:
# Leitura do sensor
sensor.measure()
temperatura = sensor.temperature()
umidade = sensor.humidity()
# Controle do LED
estado_led = 1 if temperatura >= LIMIAR else 0
led.value(estado_led)
# Exibe no console
print(f"Temp: {temperatura:.1f}°C, Umidade: {umidade:.1f}%, LED: {estado_led}")
# Publica se acima do limiar
if temperatura >= LIMIAR:
publicar_dados(temperatura, umidade, estado_led)
else:
print("Temperatura abaixo do limiar - não publicando")
except OSError as e:
print("Erro no sensor DHT:", e)
except Exception as e:
print("Erro geral:", e)
time.sleep(2)