frommachineimportPin,PWMfromutimeimportsleep# lower right corner with USB connector on topSPEAKER_PIN=16# create a Pulse Width Modulation Object on this pinspeaker=PWM(Pin(SPEAKER_PIN))speaker.duty_u16(1000)speaker.freq(300)# 1 Kilohertzsleep(.5)# wait a 1/4 secondspeaker.duty_u16(0)sleep(.25)speaker.duty_u16(1000)speaker.freq(800)sleep(.5)speaker.duty_u16(0)sleep(.25)speaker.duty_u16(1000)speaker.freq(400)sleep(.5)# turn off the PWM speaker.duty_u16(0)
Using Variables
We can also put the time each tone stays on and the space between the tones into variables so it is easier to modify the values in a single place.
1234
# set the time each tone will be onONTIME=.5# the time between the tonesOFFTIME=.100
frommachineimportPin,PWMfromutimeimportsleep# lower right corner with USB connector on topSPEAKER_PIN=16# create a Pulse Width Modulation Object on this pinspeaker=PWM(Pin(SPEAKER_PIN))# the time each tone will be onON_TIME=.25# the time between the tonesOFF_TIME=.1# Low tonespeaker.duty_u16(1000)speaker.freq(300)sleep(ON_TIME)speaker.duty_u16(0)sleep(OFF_TIME)# High tonespeaker.duty_u16(1000)speaker.freq(800)sleep(ON_TIME)speaker.duty_u16(0)sleep(OFF_TIME)# Medium tonespeaker.duty_u16(1000)speaker.freq(400)sleep(ON_TIME)# turn off the PWM speaker.duty_u16(0)
Experiments
Change the ON_TIME in the above program. What is the shortest time that you can still hear?
Change the order of the Low, High, Medium around. What is the most pleasing to your ears?
What order would you suggest for the start of a game and what order would you like for a "Game Over" sound?