import network
import time
from machine import Pin, PWM
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "temperatura_freezer"
MQTT_TOPIC_RCV_LED = "wokwi-led"
MQTT_TOPIC_RCV_BUZ = "wokwi-buz"
sensor = dht.DHT22(Pin(15))
led = Pin(12, Pin.OUT)
buzzer = PWM(Pin(13), freq=440)
servo = PWM(Pin(14), freq=50)
led_status = 0
buzzer_status = 0
servo_status = False
def callback(topic, msg):
global led_status
global buzzer_status
global servo_status
print("Recebido de {}: {}".format(topic, msg))
if topic.decode() == MQTT_TOPIC_RCV_LED:
if msg.decode() == "1":
led_status = 1
else:
led_status = 0
elif topic.decode() == MQTT_TOPIC_RCV_BUZ:
if msg.decode() == "1":
buzzer_status = 1
else:
buzzer_status = 0
elif topic.decode() == MQTT_TOPIC_RCV_SER:
if msg.decode() == "1":
servo_status = 1
else:
servo_status = 0
print("Connecting to 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(" Connected!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
client.set_callback(callback)
client.subscribe(MQTT_TOPIC_RCV_LED)
client.subscribe(MQTT_TOPIC_RCV_BUZ)
def sense_temperature():
sensor.measure()
temp = sensor.temperature()
# Cria a mensagem a ser enviada em formato JSON
message = ujson.dumps({
"sensor_id": "1",
"temp": temp,
"led": led_status,
"buz": buzzer_status
})
if temp > 16.0:
if led_status == 1:
led.on()
else:
led.off()
if temp > 20:
if buzzer_status == 1:
buzzer.duty(512) # Liga o buzzer
else:
buzzer.duty(0)
# Ativa o servo motor
else:
led.off() # Desliga o LED
buzzer.duty(0) # Desliga o buzzer
print("Enviando para {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
while True:
client.check_msg()
sense_temperature()
# Verifica se o servo motor deve ser desativado