Home CodePython Microbit and a buzzer examples

Microbit and a buzzer examples

by shedboy71

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

buzzer-300x300

Now we will show a couple of basic examples

 

Code

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

[codesyntax lang=”python”]

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)

[/codesyntax]

 

The next example will play a different tone depending on whether button a or button b is pressed

[codesyntax lang=”python”]

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()

[/codesyntax]

You may also like

Leave a Comment