from machine import Pin, ADC, PWM
import time
# CONFIGURAR GPIO => General Purpose In/Out
BTN_PULLUP_GPIO = 14
BTN_PULLDOWN_GPIO = 13
LED_ROJO_GPIO = 23
LED_VERDE_GPIO = 22
LED_PWM_GPIO = 21
# Pines ADC [Analog Digital Converter]
LDR_ADC_GPIO = 34 # Solo entrada
POT_ADC_GPIO = 35 # Solo entrada
# VARIABLES DE LAS ENTRADAS DIGITALES
btn_pullup_pin = Pin(BTN_PULLUP_GPIO, Pin.IN)
btn_pulldn_pin = Pin(BTN_PULLDOWN_GPIO, Pin.IN)
# VARIABLES DE LAS ENTRADAS ANALÓGICAS
ldr = ADC(Pin(LDR_ADC_GPIO))
pot = ADC(Pin(POT_ADC_GPIO))
# Rango típico de lectura en ESP32 con MicroPython: 0..4095
ldr.atten(ADC.ATTN_11DB) # Permite leer hasta ~3.3V
pot.atten(ADC.ATTN_11DB)
ldr.width(ADC.WIDTH_12BIT)
pot.width(ADC.WIDTH_12BIT)
# VARIABLES DE LAS SALIDAS
led_rojo = Pin(LED_ROJO_GPIO, Pin.OUT)
led_verde = Pin(LED_VERDE_GPIO, Pin.OUT)
led_pwm = PWM(Pin(LED_PWM_GPIO), freq=1000)
led_pwm.duty(0)
print("Leyendo botones...")
t_print = time.ticks_ms()
while True:
#Lecturas actuales digitales
v_up = btn_pullup_pin.value()
v_dn = btn_pulldn_pin.value()
#Lecturas actuales análogas
ldr_raw = ldr.read() # 0..4095
pot_raw = pot.read() # 0..4095
# Opcional: normalizar a porcentaje (0..100)
ldr_pct = int((ldr_raw * 100) / 4095)
pot_pct = int((pot_raw * 100) / 4095)
#Control directo de Leds
if v_up == 0: # Pull-up
led_verde.value(1)
else:
led_verde.value(0)
led_rojo.value(1 if v_dn == 1 else 0) # Pull-down
# Convertir el potenciometro en PWM (0 - 1023)
duty_pwm = int((pot_raw * 1023) / 4095)
led_pwm.duty(duty_pwm)
# Debug (muestra valores cada 300 ms)
if time.ticks_diff(time.ticks_ms(), t_print) >= 300:
t_print = time.ticks_ms()
print(
"UP: ", v_up,
"DN: ", v_dn,
"| LDR:", ldr_raw, f"({ldr_pct}%)",
"| POT:", pot_raw, f"({pot_pct}%)",
"| PWM:", duty_pwm
)
time.sleep_ms(10)