import machine
import time

ENTRANCE_BUTTON_PIN = 34
EXIT_BUTTON_PIN = 35

LED_PINS = [2, 4, 5, 13, 14, 16, 17, 18]

MAX_CARS = 8
MIN_CARS = 0

DEBOUNCE_DELAY_MS = 200

entrance_button = machine.Pin(ENTRANCE_BUTTON_PIN, machine.Pin.IN, machine.Pin.PULL_DOWN)
exit_button = machine.Pin(EXIT_BUTTON_PIN, machine.Pin.IN, machine.Pin.PULL_DOWN)

leds = []
for pin_num in LED_PINS:
    led = machine.Pin(pin_num, machine.Pin.OUT)
    leds.append(led)

car_count = 0

last_entrance_button_state = 0
last_exit_button_state = 0
last_entrance_press_time = 0
last_exit_press_time = 0

def update_leds(count):
    for i in range(len(leds)):
        if i < count:
            leds[i].value(1)
        else:
            leds[i].value(0)

print("Smart Entry-Exit Monitoring System Started")
update_leds(car_count)

while True:
    current_time_ms = time.ticks_ms()

    current_entrance_button_state = entrance_button.value()
    current_exit_button_state = exit_button.value()

    if current_entrance_button_state == 1 and last_entrance_button_state == 0:
        if time.ticks_diff(current_time_ms, last_entrance_press_time) > DEBOUNCE_DELAY_MS:
            if car_count < MAX_CARS:
                car_count += 1
                print(f"Car entered. Current count: {car_count}")
                update_leds(car_count)
            else:
                print("Traffic unit full. Cannot enter.")
            last_entrance_press_time = current_time_ms

    if current_exit_button_state == 1 and last_exit_button_state == 0:
        if time.ticks_diff(current_time_ms, last_exit_press_time) > DEBOUNCE_DELAY_MS:
            if car_count > MIN_CARS:
                car_count -= 1
                print(f"Car exited. Current count: {car_count}")
                update_leds(car_count)
            else:
                print("Traffic unit empty. Cannot exit.")
            last_exit_press_time = current_time_ms

    last_entrance_button_state = current_entrance_button_state
    last_exit_button_state = current_exit_button_state