3.3 Passive buzzer

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.

image-20220209095936443

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

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.