import machine
import dht
import utime
import network
import urequests
# --- Configurações de Rede e API ---
SSID = "Wokwi-GUEST"
PASSWORD = ""
API_KEY = "UNIFJJFS2MM6100P"
URL_BASE = "http://api.thingspeak.com/update"
# --- Configuração dos Pinos ---
pino_dados = machine.Pin(15)
sensor = dht.DHT22(pino_dados)
led_vm = machine.Pin(13, machine.Pin.OUT) # Vermelho (>= 40°C)
led_az = machine.Pin(12, machine.Pin.OUT) # Azul (< 10°C)
led_vd = machine.Pin(11, machine.Pin.OUT) # Verde (20°C a 25°C)
# --- Função de Conexão Wi-Fi ---
def conecta_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Conectando ao Wi-Fi do Wokwi...')
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
utime.sleep(0.5)
print('Conectado! IP:', wlan.ifconfig()[0])
conecta_wifi()
print("Sistema de Monitoramento Ativo!")
while True:
try:
# 1. Medição do Sensor
sensor.measure()
temp = sensor.temperature()
umid = sensor.humidity()
print("\n--- Dados Coletados ---")
print("Temperatura: {:.1f}°C | Umidade: {:.1f}%".format(temp, umid))
# 2. Lógica dos LEDs (Resposta Imediata)
led_vm.value(1 if temp >= 40 else 0)
led_vd.value(1 if 20 <= temp <= 25 else 0)
led_az.value(1 if temp < 10 else 0)
# 3. Envio para o ThingSpeak (Field1=Temp, Field2=Umid)
link = "{}?api_key={}&field1={}&field2={}".format(URL_BASE, API_KEY, temp, umid)
print("Enviando para a Nuvem...")
res = urequests.get(link)
if res.status_code == 200:
print("Sucesso! Registro ID:", res.text)
else:
print("Erro no Servidor:", res.status_code)
res.close()
# 4. Delay de 20 segundos (Segurança para o ThingSpeak)
print("Aguardando 20s para a próxima leitura...")
utime.sleep(20)
except Exception as e:
print("Erro durante a operação:", e)
utime.sleep(5)