from machine import Pin, PWM, time_pulse_us
import time
# =========================
# Pins
# =========================
TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)
SERVO = PWM(Pin(19), freq=50)
GREEN_LED = Pin(25, Pin.OUT)
YELLOW_LED = Pin(26, Pin.OUT)
RED_LED = Pin(27, Pin.OUT)
ENTRY_BUTTON = Pin(21, Pin.IN, Pin.PULL_UP)
EXIT_BUTTON = Pin(22, Pin.IN, Pin.PULL_UP)
# =========================
# Parking settings
# =========================
MAX_CAPACITY = 15
cars = 0
# =========================
# Servo function
# =========================
def gate_open():
SERVO.duty(77)
time.sleep(1)
def gate_close():
SERVO.duty(40)
time.sleep(1)
# =========================
# Ultrasonic function
# =========================
def get_distance():
TRIG.value(0)
time.sleep_us(2)
TRIG.value(1)
time.sleep_us(10)
TRIG.value(0)
duration = time_pulse_us(ECHO, 1, 30000)
if duration < 0:
return 999
distance = (duration * 0.0343) / 2
return distance
# =========================
# Parking LEDs
# =========================
def update_leds():
GREEN_LED.value(0)
YELLOW_LED.value(0)
RED_LED.value(0)
if cars >= MAX_CAPACITY:
RED_LED.value(1)
elif cars >= 10:
YELLOW_LED.value(1)
else:
GREEN_LED.value(1)
# =========================
# Start system
# =========================
update_leds()
gate_close()
print("Smart Parking System Started")
print("Capacity:", MAX_CAPACITY)
# =========================
# Main loop
# =========================
while True:
distance = get_distance()
print("Cars:", cars, "| Distance:", distance, "cm")
# Entry button
if ENTRY_BUTTON.value() == 0:
if cars < MAX_CAPACITY:
cars += 1
print("Car entered!")
print("Cars:", cars)
gate_open()
time.sleep(1)
gate_close()
update_leds()
time.sleep(0.5)
else:
print("Parking FULL!")
RED_LED.value(1)
time.sleep(0.5)
# Exit button
if EXIT_BUTTON.value() == 0:
if cars > 0:
cars -= 1
print("Car exited!")
print("Cars:", cars)
gate_open()
time.sleep(1)
gate_close()
update_leds()
time.sleep(0.5)
time.sleep(0.1)