#Completed game - with automatic light avoidance
from machine import Pin,ADC,PWM
from time import sleep
#Configure the servo pins for PWM output
servo1=PWM(Pin(0))
servo2=PWM(Pin(1))
servo1.freq(50)
servo2.freq(50)
LDR=ADC(Pin(28)) #Configure LDR potential divider pin as ADC input
buzzer=PWM(Pin(14)) #Configure buzzer pin for PWM output
score=0 #Start game with no points
def reset():
'''Reset score variable and provide user feedback before a new game'''
global score, servo1Value, servo2Value
servo1Value=5000
servo2Value=5000
score=0
beep(2)
print("Ready for new game")
def beep(numBeeps):
'''Turn the buzzer on and off a given number of times'''
print("Beep")
for i in range(numBeeps):
buzzer.duty_u16(1000)
buzzer.freq(1000)
sleep(0.2)
buzzer.duty_u16(0)
sleep(0.1)
def winningSound():
'''Play a nice winning sound'''
print("Winner!")
beep(3)
buzzer.duty_u16(5000)
#add a better winning sound here - eg loop through a range of frequencies in quick succession
reset()
from random import randint
while True:
if LDR.read_u16()<5000: #Strong light detected - change this value to suit your room and LDR
servo1Value=servo1Value+randint(-500,500)
servo2Value=servo2Value+randint(-500,500)
if servo1Value<3000:
servo1Value=3000
if servo1Value>7000:
servo1Value=7000
if servo2Value<3000:
servo2Value=3000
if servo2Value>7000:
servo2Value=7000
servo1.duty_u16(servo1Value)
servo2.duty_u16(servo2Value)
score=score+10
buzzer.freq(score+100)
buzzer.duty_u16(score+1000)
print(score)
if score>1000: #If the game has been won, play a sound and get ready for the next round
winningSound()
reset()
else: #Strong light not detected .. do nothing (turn the buzzer off)
buzzer.duty_u16(0)
sleep(0.1)