I thought the buzzer was the easiest, but it is indeed the hardest. If you want to be able to sing it, you have to learn some music.
The onboard buzzer should be an active buzzer. The simplest usage is to make a sound at a high level and no sound at a low level. The code is as follows:
from machine import Pin
import time
beep = Pin(16,Pin.OUT)
beep.on() #发声
time.sleep(2)
beep.off() #不发声
If you want to generate music, you need to use the PWM module. I was confused by the number of notes in the library that everyone called. I thought there were only do, re, mi, fa, sol, la, si. But what I saw in the library were indeed C, C# and the like. So I supplemented my knowledge of notes and asked chatGPT this time.
It can be seen that the frequency corresponding to the C note is 256hz. If it is one octave higher, the frequency will be twice as high.
Then there is the correspondence between each note and do, re, mi and the corresponding frequency. Therefore, if you want to make a do sound, the PWM frequency should be 261Hz, and the duty cycle should be set to 50%. So the code to make do, re, mi, fa, sol, la, si is as follows:
from machine import Pin,PWM
import time
yinfu = [261,293,330,349,392,440,494]
beep = PWM(Pin(16))
for i in range(7):
beep.freq(yinfu[i])
beep.duty_u16(0x8000)
time.sleep(1)
beep.deinit()
If you want to play music, it is best to call other libraries, such as
.