1. Learning Objectives
In this course, we will learn how to use active buzzers.
2. About Hardware
We need use buzzer on Pico robot car.
Passive buzzers use the phenomenon of electromagnetic induction to attract or repel the electromagnet and permanent magnet formed after the voice coil is connected to the alternating current to push the diaphragm to sound. Sound, in the control, we generally use PWM to control the passive buzzer to emit sound.
3. About code
Code path: Code -> 1.Basic course -> 3.Passive buzzer.py
from machine import Pin, PWM
import time
# set buzzer pin
BZ = PWM(Pin(22))
BZ.freq(1000)
# Initialize music
CM = [0, 330, 350, 393, 441, 495, 556, 624]
song = [CM[1],CM[1],CM[5],CM[5],CM[6],CM[6],CM[5],CM[4],CM[4],CM[ 3], CM[3], CM[2], CM[2], CM[1],]
beat = [ 0.5,0.5,0.5,0.5,0.5,0.5,1,0.5,0.5,0.5,0.5,0.5,0.5,1,]
# music
def music():
print('Playing song...')
for i in range(len(song)):
BZ.duty_u16(500)
BZ.freq(song[i])
time.sleep(beat[i])
BZ.duty_u16(0)
time.sleep(0.01)
#play music
music()
print("Ending")
from machine import Pin, PWM
The machine library contains all the instructions that MicroPython needs to communicate with Pico and other MicroPython-compatible devices, extending the language of physical computing, here only the Pin and PWM libraries are used.
import time
The "time" library. This library handles everything time related, from measuring it to inserting delays into programs. The unit is seconds.
BZ = PWM(Pin(22))
Set IO22 as a PWM output pin to control the buzzer.
BZ.freq(1000)
Set the PWM frequency to 1000.
BZ.duty_u16(0)
When the value is 0, the sound is turned off, and when the value is 500, the sound is turned on.
music()
By calling the music() function, a for loop is used in the function to play the pre-written sounds of different frequencies one by one, so as to realize the playback of music.
4. Experimental Phenomenon
After the code is downloaded, we can hear the buzzer playing the music star, and the printf shell will printf "Ending" after the music is over.