from machine import Pin, PWM, ADC
import time
import dht
import network
import urequests
# ==================== CONFIGURAÇÃO ====================
sensor = dht.DHT22(Pin(4))
# LEDs temperatura (suas cores reais)
led_verde = Pin(2, Pin.OUT) # BAIXO < 18°C
led_amarelo = Pin(13, Pin.OUT) # MÉDIO 18 a 25°C
led_vermelho = Pin(14, Pin.OUT) # ALTO > 25°C
# PIR + Buzzer
pir = Pin(5, Pin.IN)
buzzer = Pin(15, Pin.OUT)
# Porta Automática
servo = PWM(Pin(18))
servo.freq(50)
trig = Pin(19, Pin.OUT)
echo = Pin(21, Pin.IN)
# LDR (Sensor de Luz)
ldr = ADC(Pin(34))
ldr.atten(ADC.ATTN_11DB)
led_luz = Pin(23, Pin.OUT)
# ==================== WIFI + THINGSPEAK ====================
API_KEY = "6BQGHMJECODEKRLL"
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
print("🔄 Conectando ao WiFi...")
while not wifi.isconnected():
time.sleep(1)
print("✅ WiFi conectado!", wifi.ifconfig())
# ==================== VARIÁVEIS GLOBAIS ====================
total_vagas = 10
vagas_ocupadas = 4
last_parking_print = 0
parking_update_count = 0
door_open = False
door_open_time = 0
last_dht_time = 0
last_send_time = 0
last_alert_time = 0
temp = 0
umid = 0
nivel = "DESCONHECIDO"
motion_detected = False
dht_lido = False # ← NOVO: só envia depois da primeira leitura
# ==================== FUNÇÕES ====================
def set_servo(angle):
duty = int(40 + (angle * (115 - 40) / 180))
servo.duty(duty)
def get_distance():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
timeout = time.ticks_us() + 30000
while echo.value() == 0:
if time.ticks_us() > timeout: return 999
t1 = time.ticks_us()
timeout = time.ticks_us() + 30000
while echo.value() == 1:
if time.ticks_us() > timeout: return 999
t2 = time.ticks_us()
dt = time.ticks_diff(t2, t1)
return (dt * 0.0343) / 2
def classificar_temperatura(temperatura):
if temperatura < 18:
return "BAIXO"
elif 18 <= temperatura <= 25:
return "MÉDIO"
else:
return "ALTO"
# ==================== INICIALIZAÇÃO ====================
print("=== SISTEMA IoT EVOLUÍDO - CANAL 3337600 ===")
print("Enviando Temperatura (Field1) + Umidade (Field2)")
set_servo(0)
while True:
current_time = time.ticks_ms()
# ==================== DHT22 + CLASSIFICAÇÃO ====================
if time.ticks_diff(current_time, last_dht_time) >= 2000:
try:
sensor.measure()
temp = sensor.temperature()
umid = sensor.humidity()
dht_lido = True
nivel = classificar_temperatura(temp)
led_verde.value(1 if nivel == "BAIXO" else 0)
led_amarelo.value(1 if nivel == "MÉDIO" else 0)
led_vermelho.value(1 if nivel == "ALTO" else 0)
print(f"🌡️ Temperatura: {temp}°C | Umidade: {umid}% → {nivel}")
if temp > 30 and time.ticks_diff(current_time, last_alert_time) >= 10000:
print("🚨 ALERTA! Temperatura muito alta!")
last_alert_time = current_time
except OSError:
print("❌ Erro ao ler DHT22...")
last_dht_time = current_time
# ==================== PIR + BUZZER ====================
if pir.value() == 1:
buzzer.value(1)
if not motion_detected:
print("🚨 Movimento detectado!")
motion_detected = True
else:
buzzer.value(0)
motion_detected = False
# ==================== PORTA AUTOMÁTICA ====================
try:
dist = get_distance()
if dist < 999:
if dist < 20 and not door_open:
print(f"✅ Aproximação detectada! ({dist:.1f} cm) → ABRINDO")
set_servo(90)
door_open = True
door_open_time = current_time
elif door_open and time.ticks_diff(current_time, door_open_time) >= 3000:
print("Fechando porta...")
set_servo(0)
door_open = False
except:
pass
# ==================== SENSOR DE LUZ (LDR) ====================
valor_ldr = ldr.read()
if valor_ldr < 1800:
led_luz.value(1)
else:
led_luz.value(0)
# ==================== SISTEMA DE ESTACIONAMENTO ====================
if time.ticks_diff(current_time, last_parking_print) >= 8000:
parking_update_count += 1
vagas_livres = total_vagas - vagas_ocupadas
if parking_update_count % 3 == 0 and vagas_ocupadas < total_vagas:
vagas_ocupadas += 1
print("🚘 Carro entrou no estacionamento!")
elif parking_update_count % 5 == 0 and vagas_ocupadas > 0:
vagas_ocupadas -= 1
print("🚗 Carro saiu do estacionamento!")
print("🚗 SISTEMA DE ESTACIONAMENTO")
print(f"Vagas livres: {vagas_livres}")
print(f"Vagas ocupadas: {vagas_ocupadas}\n")
last_parking_print = current_time
# ==================== ENVIO PARA THINGSPEAK (CORRIGIDO) ====================
if dht_lido and time.ticks_diff(current_time, last_send_time) >= 20000:
print(f"📤 Tentando enviar → Temp: {temp}°C | Umidade: {umid}%")
url = f"http://api.thingspeak.com/update?api_key={API_KEY}&field1={temp}&field2={umid}"
try:
response = urequests.get(url)
print(f"✅ Status ThingSpeak: {response.status_code}")
response.close()
except Exception as e:
print(f"❌ Erro ao enviar: {e}")
last_send_time = current_time
# ==================== SISTEMA CONTÍNUO INTELIGENTE ====================
if nivel == "ALTO" and valor_ldr < 1800 and pir.value() == 1:
print("🌟 SISTEMA INTELIGENTE: Temperatura alta + escuro + movimento!")
print("→ Abrindo porta automaticamente para ventilação de emergência")
set_servo(90)
door_open = True
door_open_time = current_time
buzzer.value(1)
time.sleep(0.1)
buzzer.value(0)
time.sleep(0.1)
buzzer.value(1)
time.sleep(0.2)
time.sleep(0.3)Loading
esp32-devkit-c-v4
esp32-devkit-c-v4