How to Use a Piezo Speaker With the Raspberry Pi to Play Sounds
Have you ever before enquired on your own how those little teddy bear playthings earn cogent? Odds are, you were paying exhilaration to a piezoelectric agent. You can earn your super own to play sounds and music by earning earn utility of of a piezo agent with the Raspberry Pi!
- What Is a Piezo Audio agent?
- What You Requirement for the Project
- How to Employ a Piezo Audio agent Via Raspberry Pi
- Code Description
- How Is the Reliable Created
- Sometimes Enquired Questions
Also read: How to Employ Pushbuttons Via Raspberry Pi GPIO Pins
What Is a Piezo Audio agent?
Piezo agents incorporate a remarkable asset labelled a “piezo element” that is practiced of showing the piezoelectric affect, a process amasses an electrical penalty when you hit something steadfast.

Many steadfast things, advice rocks or salt, are steadfast granted that their atoms are packed tightly with each other. This clause is labelled “crystal appearance.”
In some wares, a crystal textures can bend or avail pressed when sufficient burden is used to it. This renders some atoms keep close to numerous other atoms that they usually wouldn’t rest next off to.
In piezoelectric wares or piezo treasures, these atoms have different fines: one autocratic and the numerous other unfavorable. The minute these atoms of different fines avail close with each other, they earn electricity ensue.

You can in addition do the different – apply an electrical arena on piezo treasures to earn crystal textures bend, adjusting the asset’s unexpurgated chisel. When earning earn utility of of a piezo agent, you’re rendering the piezo element inside dedication and widen so fast that it shakes and renders a cogent.
Also read: How to Manipulate your Raspberry Pi through Windows through SSH
What You Requirement for the Project
Making earn utility of of piezo agents with the Raspberry Pi to evoke sounds is as infected as rendering LEDs blink. You simply last offer a couple of things and a numerous code. You won’t last offer a resistor.
- Piezo agents
- 2 male-to-female jumper wires
- Raspberry Pi
How to Employ a Piezo Audio agent Via Raspberry Pi
- Open your favored code editor and paste the working together with code:
# The frequencies in this code was based on the note frequencies found at: # https://pages.mtu.edu/~suits/notefreqs.html # Tuned at A4 = 440Hz. import RPi.GPIO as GPIO from time import sleep GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) pin7 = GPIO.PWM(7, 100) pin7.start(50) while True: GPIO.output(7, GPIO.HIGH) pin7.ChangeFrequency(16.35) # C0 sleep(1) pin7.ChangeFrequency(261.63) # C4 sleep(1) pin7.ChangeFrequency(293.66) # D4 sleep(1) pin7.ChangeFrequency(329.63) # E4 sleep(1) pin7.ChangeFrequency(349.23) # F4 sleep(1) pin7.ChangeFrequency(392.00) # G4 sleep(1) pin7.ChangeFrequency(440.00) # A4 sleep(1) pin7.ChangeFrequency(493.88) # B4 sleep(1) pin7.ChangeFrequency(523.25) # A5 sleep(1.5) pin7.ChangeFrequency(16.35) # C0 sleep(1) GPIO.output(7, GPIO.LOW) sleep(1)
- Save as “rpi-piezo.py” or any kind of filename you pine, as long as it expires with the “.py” document extension, after that closed down the Raspberry Pi.
- Now it’s time to build the circuit. Affix the autocratic pin or wire to pin 7 and the numerous other pin to GND. Some piezo treasures have a “+” signs and symptom verifying which pin is autocratic. Others have wires sticking out – as always, a red wire prepares for autocratic.

If you’re owning annoy peeking for pin 7, grip your Raspberry Pi in a means that the GPIO pins are sticking to the proper, after that appearance at the GPIO pins. The optimal-disowned pin last offer to be pin 1 and to its proper is pin 2. Listed under pin 1 is pin 3, and to its proper is pin 4 and so on.

- Power up your Raspberry Pi and amenable the incurable.
- Get forced in the folder in which you conserved “rpi-piezo.py” through the incurable earning earn utility of of
cd
. Here’s an example:cd MTE/experiments/rpi-piezo
. The folder “rpi-piezo” contains our “rpi-piezo.py” script.
- Now it’s time to sprinted the Python script. Go into
python3 rpi-piezo.py
and reimbursement exhilaration to the sounds of the C monumental scale!
Also read: How to Revolve Your Raspberry Pi proper into a Video Conferencing Station
Code Description
The code can appearance advice a oversized mix-up initially peek, so enable’s separate it proper into 3 sectors:
- Import commands
- Arrangement commands
- Gnarled commands
This isn’t a standardized organizing – it was created granted that it’s always a nice habit to divide your code proper into deliciously identifiable sectors. It renders things less complicated when you’re trying to modification any kind of part of the code.
Import Commands
This is in which you enumerate which modules you’re “importing” proper into your code. The import commands incorporate 2 blathers of code.
import RPi.GPIO as GPIO from time import sleep
import RPi.GPIO as GPIO
tells Python that you’re earning earn utility of of the RPi.GPIO part to manipulate the Raspberry Pi’s GPIO pins. as GPIO
tells it that whenever you telephone call the variable GPIO
, you’re terming the RPi.GPIO part.
from time import sleep
is an additional means of terming modules. But instead of snatching the whole part, you’re simply importing the sleep()
impartial from the time
part. This can help a boatload when it comes to capability, as Python won’t have to jumble the whole part; it simply earns utility of that one impartial.
Also read: How to Mount Windows 11 on a Raspberry Pi 4
Arrangement Commands
The code in the arrangement commands is in which you “mount” or enumerate all the horribly realistic sectors in your prospectus, such as variables, placements, and pin designations. These lone have to be identified as shortly as.
GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) pin7 = GPIO.PWM(7, 100) pin7.start(50)
GPIO.setwarnings(False)
inhibits warnings from obtaining here when you sprinted the code. Ultimatums still emphasize up when your code runs effectively, yet adding this piece of code keeps ultimata messages from flooding the incurable every time you get in python3 rpi-piezo.py
. But this is much more of a individual selection – you can simply annihilate this little piece if you pine to surf through the warnings. It still works the super same.
GPIO.setmode(GPIO.BOARD)
tells Python how you pine your Raspberry Pi’s general purpose input/result (GPIO) pins to be named. There are 2 habits: BOARD and BCM.
- BOARD is a naming layout in which you name the pins based on their pin digits. Here, pin 1 is at the optimal disowned, pin 2 close to it, pin 3 under pin 1 and so on.
- BCM stands for “Broadcom.” Instead of physical pin digits, BCM picks their Broadcom SOC Network. This naming layout differs from board to board, so it can be a little piece more gleaned serviceability to adhere to if you’re earning earn utility of of BCM on a overview.
GPIO.setup(7, GPIO.OUT)
tells Python that you’re earning earn utility of of pin 7 as an result.
pin7 = GPIO.PWM(7, 100)
renders a variable, pin7
, that contains the string GPIO.PWM(7, 100)
. This shortens your code so that you can simply consumption pin7
instead of terming GPIO.PWM(7, 100)
all the time.
Ultimately, pin7.start(50)
caboodles pin 7 to PWM (Pulse Width Modulation) placement. This prepares for that whenever pin 7 is kit to HIGH
, it emits 3.3V half of the time. The rest of the time, it doesn’t emit anything (or is at 0V).
Gnarled Commands
Gnarled commands sprinted on a loophole – they return as long as you keep the script sprinting. To do so, you have to keep them indented after while True:
.
while True: GPIO.output(7, GPIO.HIGH) pin7.ChangeFrequency(16.35) # C0 sleep(1) pin7.ChangeFrequency(261.63) # C4 sleep(1) pin7.ChangeFrequency(293.66) # D4 sleep(1) pin7.ChangeFrequency(329.63) # E4 sleep(1) pin7.ChangeFrequency(349.23) # F4 sleep(1) pin7.ChangeFrequency(392.00) # G4 sleep(1) pin7.ChangeFrequency(440.00) # A4 sleep(1) pin7.ChangeFrequency(493.88) # B4 sleep(1) pin7.ChangeFrequency(523.25) # A5 sleep(1.5) pin7.ChangeFrequency(16.35) # C0 sleep(1) GPIO.output(7, GPIO.LOW) sleep(1)
GPIO.output(7, GPIO.HIGH)
rotates pin 7 on HIGH
. That pin is scrubing and presenting out a PWM signal. The impartial GPIO.output()
absorbs 2 parameters: the pin digit and whether you pine to kit it HIGH
or LOW
. If you skip to the bottom part, you detect GPIO.output(7, GPIO.LOW)
, which lugs out the different – it rotates pin 7 on LOW
.
The blathers of code in in between are simply a bunch of pin7.ChangeFrequency()
and sleep(1)
. Acclimating their parameters lets you play numerous kinds of notes.
pin7.ChangeFrequency()
is literally a much faster means form of GPIO.PWM(7, 100).ChangeFrequency()
. Making earn utility of of the much faster means form renders it less complicated to modification the pin you’re earning earn utility of of. If you didn’t enumerate pin7 = GPIO.PWM(7, 100)
previously, you would definitely have to modification the pin digit on every regularity modification you earn.
Also read: Raspberry Pi Supervise Not Massaging? Dare These Solutions
What’s inside .ChangeFrequency()
is the regularity of the PWM signal and, hence, the piezo element. Bear in mind that a piezo element is simply a steadfast crystal that carefully agreements when you enact electricity through it and loosens up when you quell. The fast having and comfortable earn sounds of rising and fall pitches, and you can manipulate the peddle by adjusting the digit inside .ChangeFrequency()
. To earn things less complicated for you, there’s a testament after each pin7.ChangeFrequency()
verifying what chit they are.
Ultimately, sleep(1)
pauses the code for one second. If you time out the code after you modification the regularity, you’d mostly have a singular chit – it’s gonna play that chit for as long as you keep the code sleeping.
Also read: How to Educational program Arduino Via Visual Workshop Code Making earn utility of of PlatformIO
How Is the Reliable Created
How lugs out it all go from a shaking piezo element to cogent, after that turn proper into something that can appear like music? It’s all about the regularity and peddle.
What we heed as sounds with our ears are literally resonances in the troposphere. The much more the troposphere shakes, the better the cogent’s peddle. We story this out on paper as waves of rising and fall patterns and give it an SI gadget, i.e., a gadget of measurement: Hz (which stands for Hertz). Reliable waves with much more Hz vibrate much faster than those with less. We humans can hear cogent waves shaking someplace in between 20Hz and 20,000Hz.
When you marketed ChangeDutyCycle()
, you switched over the digit of times that the piezo element would definitely vibrate over time, i.e., the regularity. Hz is a ordinance of the regularity of resonances in the troposphere.
To modification the cogent in a means that at the horribly least appears like music, you have to modification the regularity in a fussy means. In numerous other words, you have to tailor the peddle. Assorted regularity, peddle is a ordinance of how high or lowered a cogent sounds to our ears. By adjusting the peddle, you’re rendering something currently close to music.

Image resource: Unsplash
Of training course, there is much more to rendering music than simply adjusting pitches. You in addition last offer peddle period to earn a chit. That’s in which sleep()
goes – you earn the Raspberry Pi keep at a passed on peddle for a information quantity of time to give you a relevant chit!
Also read: How to Educational program an Arduino with a Raspberry Pi
Sometimes Enquired Questions
What is the difference in between a piezo agent and a magnetic agent?
Piezo agents consumption a shaking piezo element to evoke cogent. They are sporadically administered of ceramic and are usually marketed in buzzers. At the super same time, magnetic agents consumption electromagnets that vibrate plastic membranes. They are marketed in smartphones and headsets.
Execute piezo treasures have polarity?
Practically, of training course. The piezo element inside piezo agents bends one means if you apply voltage from one side and the numerous other means if you overturn it.
Besides agents, what else are piezo treasures marketed for?
Merely about anything that owns something to do with strains and vibration owns piezo treasures. This includes accelerometers, microphones, guitar pick-ups, and agents. But there’s in addition one weird thing that owns them: lighters consumption them to earn the turn on that lights a fire.
Images and screenshots by Terenz Jomar Dela Cruz