from machine import Pin, ADC, Timer
import time
PIN_LDR = 34 # Pino analógico para o LDR (e.g., GPIO34, um pino ADC)
PIN_MODO = 21 # Pino para o Interruptor SPDT: 0=Automático (Esquerda), 1=Manual (Direita)
PIN_UP = 14 # Pino para o botão UP
PIN_DOWN = 27 # Pino para o botão DOWN
PINS_RELE = [Pin(25, Pin.OUT), Pin(26, Pin.OUT)]
PINS_MONITORAMENTO = [Pin(16, Pin.OUT), Pin(17, Pin.OUT), Pin(5, Pin.OUT), Pin(18, Pin.OUT)]
MODO_AUTOMATICO = True
TEMPO_TOTAL_S = 0
MAX_TEMPO_S = 40
MIN_TEMPO_S = 0
INTERVALO_AJUSTE_S = 10
LDR_LIMITE_ESCURO = 1000 # Valor de ADC (0-4095). Ajuste este valor com testes.
TEMPO_DEBOUNCE_MS = 100 # Tempo para evitar repetição acidental dos botões
# LDR (Entrada Analógica)
ldr_adc = ADC(Pin(PIN_LDR))
ldr_adc.atten(ADC.ATTN_11DB)
# Switch
modo_pin = Pin(PIN_MODO, Pin.IN)
# Botões (usando PULL_UP para ler LOW quando pressionado)
up_pin = Pin(PIN_UP, Pin.IN, Pin.PULL_UP)
down_pin = Pin(PIN_DOWN, Pin.IN, Pin.PULL_UP)
last_up_press = 0
last_down_press = 0
def set_rele_leds(state):
"""Controla os 2 LEDs do Relé (True=ON, False=OFF)."""
for led in PINS_RELE:
led.value(state)
def update_monitor_leds(tempo):
"""Atualiza os 4 LEDs de monitoramento com base no tempo total (faixas de 10s)."""
num_leds_on = 0
if tempo > 0:
num_leds_on = (tempo - 1) // INTERVALO_AJUSTE_S + 1
num_leds_on = min(num_leds_on, len(PINS_MONITORAMENTO))
for i in range(len(PINS_MONITORAMENTO)):
PINS_MONITORAMENTO[i].value(i < num_leds_on)
def setup_mode(is_automatic):
"""Configura o estado inicial ao trocar de modo."""
global MODO_AUTOMATICO, TEMPO_TOTAL_S
if MODO_AUTOMATICO == is_automatic:
return
MODO_AUTOMATICO = is_automatic
print("---------------------------------------")
# Lógica de Transição
if MODO_AUTOMATICO:
print("MODO AUTOMÁTICO ATIVADO. Monitoramento: LED 1 piscando.")
TEMPO_TOTAL_S = 0
set_rele_leds(False)
for i in range(1, len(PINS_MONITORAMENTO)):
PINS_MONITORAMENTO[i].value(False)
else:
print("MODO MANUAL ATIVADO. Monitoramento: Todos os LEDs apagados.")
TEMPO_TOTAL_S = 0
set_rele_leds(False)
for led in PINS_MONITORAMENTO:
led.value(False)
def handle_up(pin):
"""Adiciona 10s ao tempo total (máx 40s)."""
global TEMPO_TOTAL_S, MODO_AUTOMATICO, last_up_press
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_up_press) < TEMPO_DEBOUNCE_MS:
return
last_up_press = current_time
if not MODO_AUTOMATICO:
TEMPO_TOTAL_S = min(TEMPO_TOTAL_S + INTERVALO_AJUSTE_S, MAX_TEMPO_S)
print(f"Botão UP pressionado. Novo tempo total: {TEMPO_TOTAL_S} segundos")
update_monitor_leds(TEMPO_TOTAL_S)
set_rele_leds(TEMPO_TOTAL_S > 0)
up_pin.irq(trigger=Pin.IRQ_FALLING, handler=handle_up)
def handle_down(pin):
"""Retira 10s do tempo total (mín 0s)."""
global TEMPO_TOTAL_S, MODO_AUTOMATICO, last_down_press
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_down_press) < TEMPO_DEBOUNCE_MS:
return
last_down_press = current_time
if not MODO_AUTOMATICO:
TEMPO_TOTAL_S = max(TEMPO_TOTAL_S - INTERVALO_AJUSTE_S, MIN_TEMPO_S)
print(f"Botão DOWN pressionado. Novo tempo total: {TEMPO_TOTAL_S} segundos")
update_monitor_leds(TEMPO_TOTAL_S)
set_rele_leds(TEMPO_TOTAL_S > 0)
down_pin.irq(trigger=Pin.IRQ_FALLING, handler=handle_down)
def blink_automatico_handler(timer):
"""Callback do Timer para o piscar do LED 1 no Modo Automático."""
if MODO_AUTOMATICO:
PINS_MONITORAMENTO[0].value(not PINS_MONITORAMENTO[0].value())
timer_blink = Timer(0)
timer_blink.init(period=500, mode=Timer.PERIODIC, callback=blink_automatico_handler)
def temporizador_callback(timer):
"""Callback do Timer principal (a cada 1 segundo) para decrementar tempo e checar LDR."""
global TEMPO_TOTAL_S, MODO_AUTOMATICO
if not MODO_AUTOMATICO:
# Lógica do Modo MANUAL
if TEMPO_TOTAL_S > 0:
TEMPO_TOTAL_S -= 1
print(f"Modo Manual. Tempo restante: {TEMPO_TOTAL_S} segundos")
update_monitor_leds(TEMPO_TOTAL_S)
if TEMPO_TOTAL_S == 0:
set_rele_leds(False)
print("TEMPORIZADOR ESGOTADO. Relé DESLIGADO.")
else:
# Lógica do Modo AUTOMÁTICO
ldr_value = ldr_adc.read()
if ldr_value < LDR_LIMITE_ESCURO:
# Escuro: Relé ON e pisca LEDs 2 e 3
set_rele_leds(True)
PINS_MONITORAMENTO[1].value(not PINS_MONITORAMENTO[1].value())
PINS_MONITORAMENTO[2].value(not PINS_MONITORAMENTO[2].value())
PINS_MONITORAMENTO[3].value(False)
print(f"Modo Automático: Escuro. LDR={ldr_value}. Relé LIGADO, LEDs 2 e 3 piscando.")
else:
# Claro: Relé e LEDs 2, 3 e 4 desligados.
set_rele_leds(False)
PINS_MONITORAMENTO[1].value(False)
PINS_MONITORAMENTO[2].value(False)
PINS_MONITORAMENTO[3].value(False)
# A mensagem de "claro" é omitida para não inundar o console.
timer_principal = Timer(1)
timer_principal.init(period=1000, mode=Timer.PERIODIC, callback=temporizador_callback)
initial_mode = modo_pin.value() == 0
setup_mode(initial_mode)
print("Sistema iniciado.")
while True:
current_value = modo_pin.value()
# Se o pino está LOW (0) -> MODO AUTOMÁTICO
if current_value == 0 and not MODO_AUTOMATICO:
setup_mode(True)
# Se o pino está HIGH (1) -> MODO MANUAL
elif current_value == 1 and MODO_AUTOMATICO:
setup_mode(False)
time.sleep_ms(50)