from machine import Pin, time_pulse_us
import time
import network
import urequests
# ==========================================
# 1. CONFIGURAÇÕES DE REDE E TELEGRAM (WOKWI)
# ==========================================
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
TELEGRAM_TOKEN = "8734653593:AAEzV15zFnaHTcEqLaNhjFWO2641tlhdjrc"
CHAT_ID = "5445687642"
# ==========================================
# 2. CONFIGURAÇÃO DOS PINOS (ESP32)
# ==========================================
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)
led = Pin(19, Pin.OUT)
buzzer = Pin(21, Pin.OUT)
btn = Pin(22, Pin.IN, Pin.PULL_UP)
# Variáveis de estado e temporização
alerta_ativo = False
tempo_inicio_deteccao = None
TEMPO_ESPERA_SEGUNDOS = 5 # Segundos necessários para confirmar o objeto
# ==========================================
# 3. FUNÇÕES DO SISTEMA
# ==========================================
def conectar_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Conectando ao Wi-Fi (Wokwi-GUEST)...")
wlan.connect(WIFI_SSID, WIFI_PASS)
tentativas = 0
while not wlan.isconnected() and tentativas < 20:
print(".", end="")
time.sleep(1)
tentativas += 1
print("")
if wlan.isconnected():
print("Wi-Fi Conectado com sucesso! IP:", wlan.ifconfig()[0])
return True
else:
print("Falha ao conectar no Wi-Fi!")
return False
def enviar_notificacao(texto):
try:
texto_codificado = texto.replace(" ", "%20")
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={CHAT_ID}&text={texto_codificado}"
resposta = urequests.get(url)
if resposta.status_code == 200:
print("[IoT] Notificação enviada para o Telegram com sucesso!")
else:
print(f"[Erro Telegram] Código HTTP {resposta.status_code}: {resposta.text}")
resposta.close()
except Exception as e:
print("[Erro] Falha na requisição de notificação:", e)
def medir_distancia():
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
duracao = time_pulse_us(echo, 1, 30000)
if duracao < 0:
return 400.0
return (duracao * 0.0343) / 2
# ==========================================
# 4. EXECUÇÃO PRINCIPAL
# ==========================================
print(">>> Sistema E-BOX Inicializado <<<")
conectar_wifi()
while True:
distancia = medir_distancia()
# 1. Objeto detectado a menos de 15 cm e alerta ainda desligado?
if 0 < distancia < 15.0 and not alerta_ativo:
if tempo_inicio_deteccao is None:
# Registra o tempo exato em que o objeto apareceu na frente do sensor
tempo_inicio_deteccao = time.time()
print(f"[E-BOX] Objeto detectado a {distancia:.1f} cm. Contando {TEMPO_ESPERA_SEGUNDOS}s para confirmar...")
else:
# Calcula há quantos segundos o objeto está parado
tempo_decorrido = time.time() - tempo_inicio_deteccao
# Se completou 5 segundos ininterruptos, dispara a notificação
if tempo_decorrido >= TEMPO_ESPERA_SEGUNDOS:
alerta_ativo = True
tempo_inicio_deteccao = None # Reseta o temporizador
# Ativa LED e Buzzer
led.value(1)
buzzer.value(1)
time.sleep(0.2)
buzzer.value(0)
msg = f"📬 [E-BOX] Confirmada nova correspondência na caixa! Distância: {distancia:.1f} cm"
print(msg)
enviar_notificacao(msg)
else:
# Se o objeto foi removido antes dos 5 segundos terminarem
if tempo_inicio_deteccao is not None and not alerta_ativo:
print("[E-BOX] Objeto removido antes de 5s. Falso alarme descartado.")
tempo_inicio_deteccao = None
# 2. Reset do alerta via botão físico
if btn.value() == 0 and alerta_ativo:
alerta_ativo = False
led.value(0)
msg_reset = "✅ [E-BOX] Correspondência recolhida. Alerta desligado."
print(msg_reset)
enviar_notificacao(msg_reset)
time.sleep(0.3)
time.sleep(0.1)