"""
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 network
import time
import dht
from machine import Pin
import ujson
import urequests # Biblioteca para requisições HTTP
# Configurações do ThingSpeak
WRITE_API_KEY = "QPJ3PHHW6NYIUA64" # Sua chave de API do ThingSpeak
CHANNEL_ID = "2671057" # Seu Channel ID do ThingSpeak
# Sensor e componentes
sensor = dht.DHT22(Pin(15))
# Conectar ao WiFi
print("Conectando ao WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Conectar à rede WiFi
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Conectado!")
# Loop principal
while True:
print("Medindo condições climáticas...")
try:
sensor.measure() # Medir temperatura e umidade
temp = sensor.temperature()
humidity = sensor.humidity()
if temp is not None and humidity is not None:
# URL para enviar dados para o ThingSpeak
url = f"https://api.thingspeak.com/update?api_key={WRITE_API_KEY}&field1={temp}&field2={humidity}"
response = urequests.get(url) # Fazer a requisição GET para enviar os dados
print(f"Dados enviados: Temp={temp}, Humidity={humidity}")
print(response.text) # Ver a resposta do ThingSpeak
else:
print("Falha ao ler do sensor")
except Exception as e:
print("Erro ao medir dados do sensor:", e)
time.sleep(15) # Aguarde 15 segundos antes da próxima medição