import machine
import time
# --- Pin Configuration ---
# Define the GPIO pins for the 8 LEDs
# Using the recommended stable output pins
led_pins_gpio = [18, 19, 12, 14, 13,21,4, 2]
led_pins = []
# Define GPIO pins for the push buttons
# Using input-only pins which require external pull-down resistors
entrance_button_pin = machine.Pin(34, machine.Pin.IN)
exit_button_pin = machine.Pin(35, machine.Pin.IN)
# --- System Variables ---
car_count = 0
max_cars = 8
# Debouncing variables to prevent multiple counts from a single press
last_entrance_press_time = 0
last_exit_press_time = 0
debounce_delay_ms = 200 # 200 milliseconds
# --- Setup ---
def setup():
"""Initializes the GPIO pins for the LEDs."""
print("System initializing...")
for pin_num in led_pins_gpio:
# Configure each LED pin as an output
led_pins.append(machine.Pin(pin_num, machine.Pin.OUT))
# Initially, turn all LEDs off
update_leds()
print("System ready. Waiting for input.")
def update_leds():
"""Updates the state of the 8 LEDs based on the car_count."""
print(f"Updating LEDs for car count: {car_count}")
for i in range(max_cars):
if i < car_count:
led_pins[i].on() # Turn LED on
else:
led_pins[i].off() # Turn LED off
# --- Main Loop ---
def loop():
"""The main logic loop that runs continuously."""
global car_count, last_entrance_press_time, last_exit_press_time
current_time = time.ticks_ms()
# --- Check Entrance Button ---
# The pin reads 1 when the button is pressed because of the external pull-down resistor setup
if entrance_button_pin.value() == 1 and time.ticks_diff(current_time, last_entrance_press_time) > debounce_delay_ms:
last_entrance_press_time = current_time # Record the time of the press
if car_count < max_cars:
car_count += 1
print(f"Car entered. Total cars: {car_count}")
update_leds()
else:
print("Garage is full. Cannot add more cars.")
# --- Check Exit Button ---
# The pin reads 1 when the button is pressed
if exit_button_pin.value() == 1 and time.ticks_diff(current_time, last_exit_press_time) > debounce_delay_ms:
last_exit_press_time = current_time # Record the time of the press
if car_count > 0:
car_count -= 1
print(f"Car exited. Total cars: {car_count}")
update_leds()
else:
print("Garage is empty. Cannot remove more cars.")
# Small delay to make the simulation stable
time.sleep_ms(10)
# --- Program Start ---
if __name__ == "__main__":
setup()
while True:
loop()