Raspberry Playing Basic Notes
First, let's try to control the buzzer to play seven basic notes: do, re, mi, fa, sol, la, si.
Hardware Connection
In this project, the electronic hardware we need to use is as follows:
• Raspberry Pi Pico
• Shield for Pi Pico
• Grove - Passive Buzzer
Attach the Pico and the Shield, and use a Grove data cable to connect the buzzer to A1.
Write a Program
If we want to use the buzzer to play music, we need to learn to control the two dimensions of the sound emitted by the buzzer: volume and tone.
For the volume, like adjusting the brightness of the LED, we can control it by changing the duty cycle of the PWM signal as well. On the other hand, since the tone of a sound is determined by its frequency, we can control it by just modifying the frequency of the PWM signal.
Let's write a program to let the buzzer send out seven notes: do, re, mi, fa, sol, la, si.
In this program, we need to define pins and use the “sleep()" function to control the duration of each note. As usual, we need to declare the function library at the beginning of the program:
from machine import Pin, PWM
from time import sleep
Next, define the pin:
buzzer = PWM(Pin(27))
Next, we need to use “freq()" and “duty_u16()" to define the tone and volume:
1 buzzer.freq(1046) #DO
2 buzzer.duty_u16(1000)
3
4 buzzer.freq(1175) #RE
5 buzzer.duty_u16(1000)
6
7 buzzer.freq(1318) #MI
8 buzzer.duty_u16(1000)
9
10 buzzer.freq(1397) #FA
11 buzzer.duty_u16(1000)
12
13 buzzer.freq(1568) #SO
14 buzzer.duty_u16(1000)
15
16 buzzer.freq(1760) #LA
17 buzzer.duty_u16(1000)
18
19 buzzer.freq(1967) #SI
20 buzzer.duty_u16(1000)
Finally, use “sleep()" to specify the duration of each note, and complete the program. The complete program is as follows:
1 from machine import Pin, PWM
2 from time import sleep
3
4 buzzer = PWM(Pin(27))
5 while True:
6
7 buzzer.freq(1046) #DO buzzer.duty_u16(1000)
8 sleep(1) buzzer.freq(1175) #RE buzzer.duty_u16(1000)
9 sleep(1) buzzer.freq(1318) #MI buzzer.duty_u16(1000)
10
Use a USB cable to connect Pico to the computer, click the “run" button to save the program to any location. Now, you can hear the buzzer play seven basic notes.