print("Hello, ESP32!")

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

#Pin definitions
SERVO_PINS = 18
BUTTON_PIN = [5,4,14,12] #GPIOS, GPIO4, GPIO14, GPIO12
I2C_SCL_PIN = 22
I2C_SDA_PIN = 21
RED_LED_PIN = 16
GREEN_LED_PIN = 17
BUZZER_PIN = 13

#Initialize components
servo = PWM(Pin(SERVO_PIN), freq=50, duty=77) #77 is the duty cycle for 0 degrees
i2C = I2C(0,scl=Pin(I2C_SCL_PIN), sda=Pin(I2C_SDA_PIN), freq=100000)
oled = SSD1306_I2C(128, 64, i2c)
red_led = Pin(RED_LED_PIN,Pin.OUT)
green_led = Pin(GREEN_LED_PIN,Pin.OUT)
buzzer = PWM(Pin(BUZZER_PIN), freq=1000, duty=0) #start with the buzzer off

#function to move the servo to a specific angle
def move_servo(angle):
    duty_cycle = int(((angle/ -1800) *77) +77)
    servo.duty(duty_cycle)
    sleep(0.5) #give time for the servo move

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

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

#main loop
while True:
    dislay_message("PRESS A BUTTON")
    button_pressed = False

    for i, button_pin in enumerate (BUTTON_PINS):
        button = Pin(button_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 = "10 ml Dispensed"
            elif i == 2:
                angle = 90
                message = "15 ml Dispensed"
            elif i == 3:
                angle = 120
                message = "20 ml 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
            move_servo(angle)
            sleep(0.5) #debounce delay
            control_outputs("complete") #turn on the green LED and turn off the buzzer
            dislay_message("")
    
    if not button_pressed:
        buzzer.duty(0) #turn off the buzzer if no button is pressed

    sleep(0.1)