import time
import machine
import utime
from hcsr04 import HCSR04
from machine import PWM

servo = PWM(machine.Pin(4), freq=50, duty=0) #d4 on data pin 

sensor1 = HCSR04(trigger_pin=14, echo_pin=12)

def sensorArray():
    return sensor1.distance_cm()


#function called when you want something to dispense
def dispense(x):
    #do things to despense with the despenser motor
    servo.duty(30)      
    time.sleep(x)
    servo.duty(90)      #closed
    time.sleep(5)
    servo.duty(0)

timeBetween = 0*60*4 #min between eating 
trigger = False #variable holding status of sensor 

firstFeed = True 

dispense(2)



while True:
    now = utime.ticks_ms()

    print(sensor1.distance_cm())
    # for 0>1 add a sensor value that indicates precense of something wanting to eat, true if here 
    if sensorArray() < 20:       #within 30 cm of the sensor
        trigger = True
    else:
        trigger = False 


    # trigger = sensor update information that makes this boolean 

    #When something is ready to be fed and it has been long enough, dispense food 
    if trigger and ((utime.ticks_ms() - now) > timeBetween*60*1000 or firstFeed) :
            if firstFeed: 
                firstFeed = False
                
            dispense(2)
            now = utime.ticks_ms()  #resets time which allows tracking of last feed






