from machine import ADC, Pin, PWM
from time import sleep, sleep_us, ticks_us, ticks_diff
import math
# ENTRADAS Y SALIDAS
# Entradas Analógicas
ntc=ADC(26) # NTC Interior
ldr_int=ADC(27) # LDR Interior
ldr_ext=ADC(28) # LDR Exterior
# Entradas / Salidas Digitales
pir=Pin(15, Pin.IN) # PIR Presencia
echo_hcsr04=Pin(17, Pin.IN) # HC-SR04 Echo
trig_hcsr04=Pin(16, Pin.OUT) # HC-SR04 Trigger
led_temp=Pin(20, Pin.OUT) # Alerta Temp fuera de rango
led_luz=Pin(21, Pin.OUT) # Alerta Luz fuera de rango
led_interior=Pin(22, Pin.OUT) # Luz Interior (Presencia)
# Salidas PWM (Servomotores a 50Hz)
servo_puerta = PWM(Pin(18))
servo_puerta.freq(50)
servo_cortina = PWM(Pin(19))
servo_cortina.freq(50)
# VALORES PARA EL CONTROL ANALOGICO
TEMP_MIN = 18.0
TEMP_MAX = 25.0
LUZ_INT_MAX = 40000 # Valor ADC Wokwi (mayor = más oscuro)
LUZ_EXT_SUFICIENTE = 20000 # Valor ADC Wokwi (menor = más luz)
DISTANCIA_PUERTA_CM = 50 # Rango de apertura de puerta
# Posiciones de Servos (Duty Cycle u16 para PWM)
SERVO_CERRADO = 1638 # Aprox 0 grados
SERVO_ABIERTO = 4915 # Aprox 90 grados
# Ciclo principal de ejecución (Scan)
while True:
# 1. MONITOREO DE CONDICIONES AMBIENTALES (Interior)
# Lectura y escalamiento de NTC a grados Celsius
adc_ntc=ntc.read_u16()
temp_celsius = 0
if adc_ntc > 0 and adc_ntc < 65535:
# Ecuación Beta para termistor NTC estándar (10k)
resistencia = 10000 / (65535 / adc_ntc - 1)
temp_celsius = 1 / (math.log(resistencia / 10000) / 3950 + 1 / 298.15) - 273.15
# Lectura LDR Interior
adc_ldr_int = ldr_int.read_u16()
# Lógica de Alertas (Fuera de rango)
if temp_celsius < TEMP_MIN or temp_celsius > TEMP_MAX:
led_temp.value(1)
else:
led_temp.value(0)
if adc_ldr_int > LUZ_INT_MAX:
led_luz.value(1)
else:
led_luz.value(0)
# 2. CONTROL DE ILUMINACIÓN INTERIOR
# Si hay presencia, se enciende la luz interior
if pir.value() == 1:
led_interior.value(1)
else:
led_interior.value(0)
# 3. CONTROL DE CORTINAS (Exterior)
adc_ldr_ext = ldr_ext.read_u16()
# Si la iluminación exterior es suficiente, abrir cortinas
if adc_ldr_ext < LUZ_EXT_SUFICIENTE:
servo_cortina.duty_u16(SERVO_ABIERTO)
else:
servo_cortina.duty_u16(SERVO_CERRADO)
# 4. CONTROL DE ACCESO AUTOMÁTICO (Puerta)
# Generar pulso de Trigger
trig_hcsr04.value(0)
sleep_us(2)
trig_hcsr04.value(1)
sleep_us(10)
trig_hcsr04.value(0)
# Capturar tiempos de Echo para cálculo
signaloff = 0
signalon = 0
timeout = ticks_us()
while echo_hcsr04.value() == 0 and ticks_diff(ticks_us(), timeout) < 30000:
signaloff = ticks_us()
while echo_hcsr04.value() == 1 and ticks_diff(ticks_us(), timeout) < 60000:
signalon = ticks_us()
# Cálculo de distancia en cm
if signalon > signaloff:
tiempo_pasado = signalon - signaloff
distancia = (tiempo_pasado * 0.0343) / 2 # Velocidad del sonido aprox.
if distancia < DISTANCIA_PUERTA_CM:
servo_puerta.duty_u16(SERVO_ABIERTO)
else:
servo_puerta.duty_u16(SERVO_CERRADO)
# Retardo del ciclo
sleep(0.1)