Microbit and a buzzer examples
MicroPython on the BBC micro:bit comes with a powerful music and sound module. It’s very easy to generate bleeps and bloops from the device if you attach a buzzer. Use crocodile clips to attach pin 0 and GND to the positive and negative inputs on the buzzer.
Here is a typical buzzer
Now we will show a couple of basic examples
We will be using music.pitch function, here is a little bit of information about this function first
music.pitch(frequency, len=-1, pin=microbit.pin0, wait=True)
Plays a pitch at the integer frequency given for the specified number of milliseconds. For example, if the frequency is set to 440 and the length to 1000 then we hear a standard concert A for one second.
If wait is set to True, this function is blocking.
If len is negative the pitch is played continuously until either the blocking call is interrupted or, in the case of a background call, a new frequency is set or stop is called.
The first example simply plays 3 different frequencies for different periods of time
from microbit import * import music while True: music.pitch(440,1000) sleep(1000) music.pitch(660,500) sleep(1000) music.pitch(880,750) sleep(1000) music.stop() sleep(1000)
The next example will play a different tone depending on whether button a or button b is pressed
from microbit import * import music while True: if button_a.is_pressed(): music.pitch(440,1000) elif button_b.is_pressed(): music.pitch(660,500) else: music.stop()
Leave a Comment
You must be logged in to post a comment.