from machine import Pin, PWM
import time
# ---------- CONFIGURACIÓN ----------
# Servo para puerta
servo = PWM(Pin(0))
servo.freq(50)
# Sensor ultrasónico 1 (entrada)
trigger1 = Pin(2, Pin.OUT)
echo1 = Pin(3, Pin.IN)
# Sensor ultrasónico 2 (salida)
trigger2 = Pin(4, Pin.OUT)
echo2 = Pin(5, Pin.IN)
# ---------- FUNCIONES ----------
def medird(trigger, echo):
trigger.low()
time.sleep_us(2)
trigger.high()
time.sleep_us(10)
trigger.low()
while echo.value() == 0:
pulsoi = time.ticks_us()
while echo.value() == 1:
pulsof = time.ticks_us()
dur = time.ticks_diff(pulsof, pulsoi)
distancia = (dur / 2) / 29.1
return distancia
def abrir_p():
print("Clave correcta. Abriendo puerta...")
servo.duty_u16(8000) # Abrir
time.sleep(3)
servo.duty_u16(2000) # Cerrar
print("Puerta cerrada")
# ---------- PROGRAMA PRINCIPAL ----------
clave_correcta = "1234"
while True:
d1 = medird(trigger1, echo1)
print("Sensor 1 (entrada): {:.1f} cm".format(d1))
if d1 < 15: # Carro esperando
clave = input("Ingrese la clave: ")
if clave == clave_correcta:
abrir_p()
else:
print("Clave incorrecta.")
# Verificamos si el carro pasó (sensor 2)
print("Esperando que el carro pase...")
while True:
d2 = medird(trigger2, echo2)
print("Sensor 2 (salida): {:.1f} cm".format(d2))
if d2 < 15:
print("Carro ha pasado.")
break
time.sleep(0.5)
time.sleep(1)