#Motion Sensor Fish Feeder 12/9/21
#Jun-Hong Chen

import time, pwmio, board, digitalio
#from analogio import AnalogIn
from adafruit_motor import servo
from adafruit_apds9960.apds9960 import APDS9960
from adafruit_debouncer import Debouncer

pwm = pwmio.PWMOut(board.D2, frequency=50, duty_cycle=0)
servo_1 = servo.Servo(pwm, max_pulse = 2500)

led = digitalio.DigitalInOut(board.D4)
led.direction = digitalio.Direction.OUTPUT
led.value = False
flash = False

button = digitalio.DigitalInOut(board.D3)
button.switch_to_input(pull=digitalio.Pull.UP)
button_1 = Debouncer(button)

i2c = board.I2C()
multi_sensor = APDS9960(i2c)
multi_sensor.enable_proximity = True

count = 0

def cycle(x):
    if x == 1:
        for angle in range(90, 136, 45):
            servo_1.angle = angle
            time.sleep(1)
    elif x == 2:
        for angle in range(135, 181, 45):
            servo_1.angle = angle
            time.sleep(1)
        for angle in range(180, 89, -45):
            servo_1.angle = angle
            time.sleep(1)
    elif x == 3:
        for angle in range(90, 44, -45):
            servo_1.angle = angle
            time.sleep(1)
    elif x == 4:
        for angle in range(45, -1, -45):
            servo_1.angle = angle
            time.sleep(1)
        for angle in range(0, 91, 45):
            servo_1.angle = angle
            time.sleep(1)

while True:
    reading = multi_sensor.proximity
    if reading >= 50:
        if count >= 5:
            led.value = True
            print("Refill Time")
            pressed = False
            while pressed == False:
                button_1.update()
                if button_1.fell:
                    print("Reset")
                    count = 0
                    led.value = False
                    pressed = True
        else:
            count += 1
            print(count)
            cycle(count)
    time.sleep(0.1)



