Skip to content
This repository has been archived by the owner on Jul 11, 2024. It is now read-only.
alienzhangyw edited this page Apr 25, 2020 · 3 revisions

There are usually two kinds of buzzer modules. One is active buzzer, which can be controlled as a digital output device. It has been mentioned here.

The other one is passive buzzer, which should be driven by a square wave in a certain frequency. Passive buzzer module

This page introduces how to use a low-level trigger passive buzzer module to play music.

https://video.zhihu.com/video/1213141393801490432

First of all, you need to find a sheet music, like the "Twinkle Twinkle Little Star" bellow.

"Twinkle Twinkle Little Star"

Then you need to know the sound frequency of each note:

Note Frequency Chart

With simple music theory, we can find that in the song "Twinkle Twinkle Little Star", the frequency of note Do is 261.63Hz, Re is 293.66Hz, and so on.

In BlockPi, We use some variables to save the frequencies we need:

Then save all the notes of the song to a list in order:

PS: I use this method to build the list because it looks good and it's convenient to modify. You can choose an easier one.

Save the duration of each note to a list in the same way:

Set the buzzer to a PWM output device. Change the frequency and the duration by traversing the list to play the notes:

PS: Set the duty cycle to 0 and sleep for 0.1 seconds is aim to simulate the pauses between notes. You can use similar method to deal with the pause note in your music.

The program is finished, just click Run to try it.

The save file is here(Right-click and Save-as).