from machine import Pin, ADC, SoftI2C
import network
import time
import ssl
import machine
import ubinascii
from umqtt_simple import MQTTClient
from time import sleep
import dht
import ssd1306
import json
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
MQTT_BROKER = 'broker.hivemq.com'
MQTT_PORT = 1883
MQTT_USER= ''
MQTT_PASSWORD = ''
MQTT_CLIENT_ID = ubinascii.hexlify(machine.unique_id())
MQTT_TOPIC = b"pedroumc/estacao"
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
time.sleep(1)
print("Wi-Fi conectado:", wlan.ifconfig())
def connect_mqtt():
client = MQTTClient(
client_id=MQTT_CLIENT_ID,
server=MQTT_BROKER,
port=MQTT_PORT,
user=MQTT_USER,
password=MQTT_PASSWORD,
ssl=False
)
client.connect()
print("MQTT conectado")
return client
connect_wifi()
client = connect_mqtt()
# PINS
sensor_dht = dht.DHT22(Pin(4))
ldr = ADC(Pin(34))
mq2 = ADC(Pin(35))
botao = Pin(14, Pin.IN, Pin.PULL_UP)
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
tela = 0
botao_anterior = 1
# Funções
def ler_dht():
sensor_dht.measure()
return sensor_dht.temperature(), sensor_dht.humidity()
def ler_ldr():
return ldr.read()
def ler_mq2():
return mq2.read()
def calc_thom(temp, umid):
thom = temp - (0.55 - 0.0055 * umid) * (temp - 14.5)
return round(thom, 1)
def interpretar_thom(thom):
if thom < 15:
return "Frio"
elif 15 <= thom < 20:
return "Levemente frio"
elif 20 <= thom < 27:
return "Confortavel"
elif 27 <= thom < 30:
return "Levemente quente"
else:
return "Desconfortavel!"
# Loop principal
while True:
temp, umid = ler_dht()
luz = ler_ldr()
gas = ler_mq2()
thom = calc_thom(temp, umid)
conforto_descricao = interpretar_thom(thom)
# Verifica se há alerta
alerta_ativo = temp > 30 or gas > 2000 or thom >= 27
# MQTT JSON
dados = {
"temperatura": temp,
"umidade": umid,
"luz": luz,
"gas": gas,
"thom": thom,
"conforto": conforto_descricao,
"alerta": alerta_ativo
}
try:
client.publish(MQTT_TOPIC, json.dumps(dados))
print("Publicado no MQTT:", dados)
except Exception as e:
print("Erro ao publicar MQTT:", e)
# Botão
botao_atual = botao.value()
if botao_anterior == 1 and botao_atual == 0:
tela = (tela + 1) % 2
sleep(0.2)
botao_anterior = botao_atual
# OLED
oled.fill(0)
if alerta_ativo:
oled.text("! ALERTA !", 0, 0)
if temp > 30:
oled.text("Temp alta: {}C".format(temp), 0, 10)
if gas > 2000:
oled.text("Gas alto: {}".format(gas), 0, 20)
if thom >= 27:
oled.text("THOM: {} ({})".format(thom, conforto_descricao), 0, 30)
else:
if tela == 0:
oled.text("Temp: {}C".format(temp), 0, 0)
oled.text("Umid: {}%".format(umid), 0, 10)
oled.text("THOM: {}".format(thom), 0, 20)
oled.text(conforto_descricao, 0, 30)
elif tela == 1:
oled.text("Luz: {}".format(luz), 0, 0)
oled.text("Gas: {}".format(gas), 0, 10)
oled.show()
sleep(5)