from machine import Pin, PWM
from time import ticks_ms, ticks_diff, sleep
import tm1637
import time

def move_servo(angle):
    # Convert angle (0-180) to duty cycle (40-115)
    duty = int((angle / 180 * 75) + 40)
    servo_motor.duty(duty)

# LED setup
green_led = Pin(5, Pin.OUT)

# Button on GPIO 12 and 32, with internal pull-up resistor
# So basically, Pin.PULL_UP means the GPIO pin is set to HIGH (3.3V) by default.
# When the button is pressed, it connects the pin directly to GND (0V),
# so the pin reads a value of 0 — the current is pulled down to ground.
start_button = Pin(4, Pin.IN, Pin.PULL_UP)
end_button = Pin(16, Pin.IN, Pin.PULL_UP)

buzzer = Pin(21, Pin.OUT)

# Display setup
tm = tm1637.TM1637(clk=Pin(15), dio=Pin(2))

# Servo Motor
servo_motor = PWM(Pin(22), freq=50)

# Variables
counting = False
counter = 0
last_update = ticks_ms()
total_price = 150

while True:
####################### Start Button Logic ##############################

    if start_button.value() == 0:
        if not start_button_pressed:
            press_time = ticks_ms()
            start_button_pressed = True
            
        else:
            held_time = ticks_diff(ticks_ms(), press_time)
            if held_time >= 1000 and not counting:
                counting = True
                green_led.on()
                move_servo(0)
    else:
        start_button_pressed = False

    time.sleep_ms(10)  # Let CPU rest — avoids 100% loop usage

######################## Start Button Logic ##############################


####################### End Button Logic ##############################

    if counting and end_button.value() == 0:
        if not end_button_pressed:
            press_time = ticks_ms()
            end_button_pressed = True

        else:
            held_time = ticks_diff(ticks_ms(), press_time)

            if held_time >= 2000 and counting:
                counting = False
                green_led.off()
                counter = 0
                buzzer.on()
                print("\n\nEEEEEEENK")
                tm.show([0x00, 0x00, 0x00, 0x00])
                move_servo(90)

                sleep(5)
                buzzer.off()
                print("Session is Done!\n")
                print(f"Please Pay: {total_price}")
                total_price = 150 # Reset the price to 150 to avoid price stacking

    else:
        end_button_pressed = False
    
    time.sleep_ms(10)  # Let CPU rest to avoid 100% loop usage

    ####################### End Button Logic ##############################
          

    if counting and ticks_diff(ticks_ms(), last_update) >= 1000:
        minutes = counter // 60
        seconds = counter % 60
        display_val = minutes * 100 + seconds
        tm.show_number(display_val)
        counter += 1
        last_update = ticks_ms()

        if counter % 10 == 0:
            total_price += 25
$abcdeabcde151015202530354045505560fghijfghij
4-Digit Display