import machine
import dht
import time
import network
import urequests
# --- Configurações de Rede e ThingSpeak ---
SSID = "Wokwi-GUEST"
PASSWORD = ""
API_KEY = "4APW68QBK76FRG1Q" # Substitua pela sua Write API Key
URL = "http://api.thingspeak.com/update"
# --- Configuração dos Pinos ---
sensor = dht.DHT22(machine.Pin(15))
led_vermelho = machine.Pin(13, machine.Pin.OUT)
led_verde = machine.Pin(12, machine.Pin.OUT)
led_azul = machine.Pin(11, machine.Pin.OUT)
TEMP_MIN = 20
TEMP_MAX = 26
# --- Função para Conectar ao Wi-Fi ---
def conecta_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Conectando ao WiFi...')
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
pass
print('Conectado! IP:', wlan.ifconfig()[0])
def atualizar_leds(temp):
led_vermelho.value(1 if temp > TEMP_MAX else 0)
led_azul.value(1 if temp < TEMP_MIN else 0)
led_verde.value(1 if TEMP_MIN <= temp <= TEMP_MAX else 0)
# Inicializa conexão
conecta_wifi()
while True:
try:
time.sleep(15) # O ThingSpeak (grátis) aceita envios a cada 15s
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
print(f"Temp: {t}°C | Umid: {h}%")
atualizar_leds(t)
# Envio para o ThingSpeak
request_url = f"{URL}?api_key={API_KEY}&field1={t}&field2={h}"
resposta = urequests.get(request_url)
if resposta.status_code == 200:
print("Dados enviados com sucesso!")
else:
print(f"Erro no envio: {resposta.status_code}")
resposta.close() # Importante fechar a conexão
except OSError as e:
print("Falha na leitura do sensor ou rede.")