import network
import time
import dht
import urequests
from machine import Pin
# ===== CONFIGURAÇÃO THINGSPEAK =====
ID_CANAL = "3316610"
API_KEY = "TTBRI4M2DUSGH8DM"
URL_BASE = "http://api.thingspeak.com/update"
# ===== CONFIGURAÇÃO HARDWARE =====
PINO_SENSOR = 15
sensor = dht.DHT22(Pin(PINO_SENSOR))
led_vm = Pin(13, Pin.OUT)
led_vd = Pin(12, Pin.OUT)
led_az = Pin(11, Pin.OUT)
TEMP_MIN = 18
TEMP_MAX = 22
# ===== FUNÇÃO CONECTAR WI-FI (Wokwi Guest) =====
def conecta_wifi():
print("Conectando ao Wi-Fi...", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Rede padrão do simulador
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.5)
print(" Conectado!")
conecta_wifi()
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(f"\nTemp: {temp}C | Umid: {hum}%")
# Lógica dos LEDs (Mantida a sua)
led_vm.off(); led_vd.off(); led_az.off()
if temp > TEMP_MAX:
led_vm.on()
elif temp < TEMP_MIN:
led_az.on()
else:
led_vd.on()
# --- ENVIO PARA O THINGSPEAK ---
print("Enviando para ThingSpeak...")
# Criamos a URL com os parâmetros: api_key, field1 (temp) e field2 (hum)
url = f"{URL_BASE}?api_key={API_KEY}&field1={temp}&field2={hum}"
resposta = urequests.get(url)
if resposta.status_code == 200:
print("Dados enviados com sucesso!")
else:
print(f"Falha no envio. Erro: {resposta.status_code}")
resposta.close()
except Exception as e:
print("Erro:", e)
# O ThingSpeak tem um limite de 15 segundos entre envios (conta gratuita)
print("Aguardando 2 segundos...")
time.sleep(20)