from machine import Pin, PWM
import time
LATCH = "closed"
MODE = "off"
RED = Pin(1, Pin.OUT)
GREEN = Pin(3, Pin.OUT)
switch = Pin(27, Pin.IN, Pin.PULL_UP)
button = Pin(28, Pin.IN, Pin.PULL_UP)
latchServo = PWM(Pin(15))
tailServo = PWM(Pin(14))
buzzer = PWM(Pin(17))
latchServo.freq(50)
tailServo.freq(50)
buzzer.freq(1000)
IR = Pin(9, Pin.IN)
def changeEyeColor(color):
if color == "red":
GREEN.value(0)
RED.value(1)
elif color == "green":
RED.value(0)
GREEN.value(1)
else:
RED.value(0)
GREEN.value(0)
def happyNoise():
buzzer.freq(1200)
buzzer.duty_u16(20000)
time.sleep(0.15)
buzzer.freq(1600)
time.sleep(0.15)
buzzer.duty_u16(0)
def angryNoise():
buzzer.freq(500)
buzzer.duty_u16(20000)
time.sleep(0.15)
buzzer.freq(100)
time.sleep(0.15)
buzzer.duty_u16(0)
def servoCenter():
tailServo.duty_u16(4850)
def servoLeft():
tailServo.duty_u16(4000)
def servoRight():
tailServo.duty_u16(5700)
def tailWag():
for _ in range(3):
servoLeft()
time.sleep(0.15)
servoRight()
time.sleep(0.15)
servoCenter()
def openLatch():
global LATCH
latchServo.duty_u16(2050)
LATCH = "open"
def closeLatch():
global LATCH
latchServo.duty_u16(4850)
LATCH = "closed"
last_button = 1
last_ir = 1
while True:
current_ir = IR.value()
if last_ir == 1 and current_ir == 0:
changeEyeColor("green")
happyNoise()
tailWag()
time.sleep(0.05)
changeEyeColor("off")
last_ir = current_ir
time.sleep(0.01)
if switch.value() == 0:
MODE = "on"
closeLatch()
else:
MODE = "off"
current_button = button.value()
if last_button == 1 and current_button == 0:
if MODE == "off":
if LATCH == "closed":
openLatch()
else:
closeLatch()
else:
changeEyeColor("red")
angryNoise()
time.sleep(0.5)
changeEyeColor("off")
last_button = current_button