from machine import Pin, I2C, PWM
import ssd1306
from time import sleep, ticks_ms, ticks_diff

button_pins = [27, 14, 12, 13]
buzzer_pin = 5
servo_pin=18

servo = PWM(Pin(servo_pin), freq=50, duty=77)
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=10000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
red_led = Pin(16, Pin.OUT)
green_led = Pin(17, Pin.OUT)
buzzer = PWM(Pin(buzzer_pin), freq=10000, duty=0)

#function to move the servo to spesific angle
def move_servo(angle):
    duty_cycle = int(((angle / -180)*77) + 77)
    servo.duty(duty_cycle)
    sleep(0.5)

#function to control LEDs and buzzer based on motor operation
def control_outputs(status):
    if status == "running":
        red_led.on()
        green_led.off()
        buzzer.duty(0) #turn off buzzer when the motor is running
    elif status  == "complete":
        red_led.off()
        green_led.on()
        buzzer.duty(520) #turn on buzzer when motor is complete

#function to display message on OLED screen
def display_message(message):
    oled.fill(1)
    oled.text(message, 10, 30, 0)
    oled.show()

#main loop
while True:
    display_message("Press a button")
    button_pressed = False

    for i, button_pin in enumerate(button_pins):
        button = Pin(button_pin, Pin.IN, Pin.PULL_UP)
        if button.value() == 0:
            button_pressed = True
            if i == 0:
                angle = 30
                message = "5ml dispensed"
            elif i == 1:
                angle = 60
                message = "10ml dispensed"
            elif i == 2:
                angle = 90
                message = "15ml dispensed"
            elif i == 3:
                angle = 120
                message = "20ml dispensed"

            volume = (i+1)*5 #calculate volume based on button press
            display_message(message)
            control_outputs("running") #turn on the red LED and turn off the buzzer indicating 
            move_servo(angle)
            sleep(0.5) #debounce delay
            control_outputs("complete") #turn on led and turn on the buzzer indicating
            display_message("")
        
        if not button_pressed:
            buzzer.duty(0) #turn off the buzzer if no button pressed
        sleep(0.1)