The Raspberry Pi Pico is a low-cost microcontroller board that makes it easy for beginners to get started with electronics projects and learn how to code.
For this project, you will learn how to read an analog signal from a potentiometer and convert it into a PWM (pulse-width modulation) signal to manipulate the frequency, or tone, of a buzzer with the help of MicroPython code.
One jumper wire (yellow in the photo) connects the left side of the potentiometer to the positive (+) rail of the breadboard. Another jumper wire connects the right side of the potentiometer to the negative (-) side of the breadboard. From the middle pin of the potentiometer, you will need to run a jumper wire to the GP26/A0 pin on the Pico.
The piezo buzzer will need to have one wire going from its negative leg to the negative breadboard rail and then another connection from its positive leg to the GP15 pin on the Raspberry Pi Pico.
You’ll also need to run a jumper wire from a GND pin on Pico to the negative rail on the breadboard, to ground it. Another jumper wire will connect the 3V3 Out pin on the Pico to the positive rail of the breadboard, to power the components.
Create the Code
You can grab the code from the MUO GitHub repository. Download the MicroPython file named piezo-buzzer.py and then load this onto your Pico via a USB-connected computer running the Thonny IDE. Check out how to get started with MicroPython on the Raspberry Pi Pico for details.
The various parts of the code do the following:
- At the top, we import the required machine, math, and time MicroPython modules.
- A buzzer variable is then assigned to pin GP15 as a PWM output.
- A potentiometer variable is assigned to the analog-to-digital converter (ADC) on Pico’s GP26/A0 pin.
- We define a scale() function that uses math functions to convert the range of the potentiometer movement to an output for the buzzer.
- The while: True infinite loop reads the potentiometer input, then uses the scale function to convert it. After checking that it hasn’t changed too much from the previous frequency, it then sends the calculated frequency to the buzzer using PWM (pulse-width modulation).
In summary, there are hundreds of pulses being sent per second and the buzzer tone will shift between 120Hz and 5kHz as the potentiometer is turned clockwise or counter-clockwise. Rotating the potentiometer alters the voltage that’s read by the Pico’s analog input pin, which in turn is used to adjust the buzzer frequency using PWM.
Run the code from Thonny (click the play icon or press F5 on your keyboard) and try it out for yourself. After your first run, will any code changes impact physical outcomes? For example, what happens if you change the range (0 to 65535)? This part of the code is located just below while True: where the frequency is defined.