"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import time
import dht
from machine import Pin
import network
import ubinascii
from umqtt.simple import MQTTClient
# Definições de pinos
DHT_PIN = Pin(4)
RELAY_HEATER = Pin(13, Pin.OUT)
RELAY_COOLER = Pin(12, Pin.OUT)
dht_sensor = dht.DHT22(DHT_PIN)
# Credenciais WiFi e servidor MQTT
ssid = "Wokwi-GUEST"
password = ""
mqtt_server = "broker.hivemq.com"
client_id ="micropython-weather-demo"
# Conectando ao WiFi
def connect_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print('IP:', sta_if.ifconfig()[0])
# Callback para mensagens MQTT
def mqtt_callback(topic, msg):
message = msg.decode()
print(f"Received '{message}' on topic '{topic.decode()}'")
if topic.decode() == "home/temperature/control":
if message == "heat_on":
RELAY_HEATER.on()
elif message == "heat_off":
RELAY_HEATER.off()
elif message == "cool_on":
RELAY_COOLER.on()
elif message == "cool_off":
RELAY_COOLER.off()
# Conectando ao servidor MQTT
def connect_mqtt():
client = MQTTClient(client_id, mqtt_server)
client.set_callback(mqtt_callback)
client.connect()
client.subscribe("home/temperature/control")
print('Connected to MQTT broker')
return client
def main():
connect_wifi()
client = connect_mqtt()
while True:
client.check_msg()
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print(f'Temperature: {temperature}°C Humidity: {humidity}%')
payload = f'Temperature: {temperature}°C Humidity: {humidity}%'
client.publish('home/temperature', payload)
# Controle automático dos relés
if temperature < 20: # Ligar aquecimento se temperatura for menor que 20°C
RELAY_HEATER.on()
else:
RELAY_HEATER.off()
if temperature > 25: # Ligar resfriamento se temperatura for maior que 25°C
RELAY_COOLER.on()
else:
RELAY_COOLER.off()
except OSError as e:
print('Failed to read sensor.')
time.sleep(2)
if __name__ == '__main__':
main()