Let's test the piezospeaker using calls to the cyberbot module's tone function. True to its name, this function instructs an I/O pin to alternate high/low electrical signals at a specific frequency, allowing a piezospeaker to emit a tone.
The tone function allows you to specify the frequency with the f parameter, and the duration of the tone in milliseconds with the ms parameter.
This piezospeaker is designed to play 4.5 kHz tones for smoke alarms, but it can also play a variety of audible tones and usually sounds best in the 1 kHz to 3.5 kHz range. The start-alert tone we’ll use is:
That will make P22 send a series of high/low signals repeating at 3 kHz (3000 times per second). The tone will last for 1000 ms, which is 1 second. The micro:bit will wait until the tone function is complete before moving on to the next command.
This example script makes a beep when it starts running, then it sends the message “Waiting for Reset” scrolling across the micro:bit LED matrix. These messages will continue indefinitely because they are in the while True: loop. If the reset button is pressed, the speaker will replay the sound.
- Enter, save, and flash the script below:
# piezospeaker_test.py from cyberbot import * bot(22).tone(3000, 1000) while True: display.scroll("Waiting for Reset")
Try this: for loops for sound effects
It is easy to make sound effects by using a for loop.
- Enter, save, and flash the script below.
# sound_effect.py from cyberbot import * for freq in range (500, 3100, 100): bot(22).tone(freq, 100)
You should hear a series of tones that increase in pitch.
Just for fun, modify the sound_effect.py script by varying the values in the range function's start, stop, and step parameters.
- Try making the tones cover a greater range of frequencies.
- Try making the tones vary only a little from one to the next, for a smoother sound.
- Try making the tones go from a higher pitch to a lower pitch, so it sounds like something is falling.
- Try making a script that sounds like a cricket.