from machine import Pin, ADC, PWM, time_pulse_us
v_ntc = VREF - 0.01
R_ntc = R_FIXED * ((VREF - v_ntc) / v_ntc)
inv_T = (1.0 / T0) + (1.0 / BETA) * math.log(R_ntc / R0)
T_C = (1.0 / inv_T) - 273.15
temp_out = not (TEMP_MIN_C <= T_C <= TEMP_MAX_C)
led_temp.value(1 if temp_out else 0)
# ---- Alerta de luz interior fuera de rango aceptable ----
luz_out = not (LUX_MIN_V <= v_ldrI <= LUX_MAX_V)
led_luz.value(1 if luz_out else 0)
# ---- Presencia y oscuridad con histeresis ----
pres = (pir.value() == 1)
if dark_state:
if v_ldrI > LDRI_OFF_V:
dark_state = False
else:
if v_ldrI < LDRI_ON_V:
dark_state = True
lamp.value(1 if (pres and dark_state) else 0)
# ---- Cortinas con histeresis por luz exterior ----
if curt_open:
if v_ldrE < LDRE_CLOSE_V:
curt_open = False
else:
if v_ldrE > LDRE_OPEN_V:
curt_open = True
curt_angle = angle_curt_open if curt_open else angle_curt_closed
us_curt = 500 + (curt_angle/180)*2000
duty_curt = int(us_curt/20000*DEF_U16)
sv_curt.duty_u16(duty_curt)
# ---- Distancia ultrasónica ----
trig.value(0); time.sleep_us(2)
trig.value(1); time.sleep_us(10)
trig.value(0)
t_us = time_pulse_us(echo, 1, 30000) # timeout ~30 ms (~5 m)
if t_us > 0:
dist_cm = (t_us * 0.0343) / 2.0
else:
dist_cm = 999.0
# ---- Puerta con histeresis por distancia ----
if door_open:
if dist_cm > DOOR_OFF_CM:
door_open = False
else:
if dist_cm < DOOR_ON_CM:
door_open = True
door_angle = angle_door_open if door_open else angle_door_closed
us_door = 500 + (door_angle/180)*2000
duty_door = int(us_door/20000*DEF_U16)
sv_door.duty_u16(duty_door)
# ---- Debug serial ----
print(
"T={:.2f}C".format(T_C),
"LDRi={:.2f}V".format(v_ldrI),
"LDRe={:.2f}V".format(v_ldrE),
"PIR={}".format(int(pres)),
"d={:.1f}cm".format(dist_cm),
"dark={} curtOpen={} doorOpen={}".format(int(dark_state), int(curt_open), int(door_open))
)
time.sleep(0.1)