Make music with the Raspberry PI!
Ever wondered how those tiny teddy bear toys make their sounds? Chances are, you were listening to a piezoelectric speaker. You can make your own for playing sounds and music by using a piezo speaker with the Raspberry Pi!
Also read: How to Use Pushbuttons With Raspberry Pi GPIO Pins
Piezo speakers contain a special material called a “piezo element”, which is capable of exhibiting the piezoelectric effect, a process wherein hitting something solid makes it generate an electric charge.
Many solid things, like rocks or salt, are solid because their atoms are packed tightly together. This arrangement is called their “crystal structure”.
In some materials, their crystal structures can bend or get squeezed when enough force is applied to them. This makes some atoms stay beside other atoms that they normally wouldn’t sit next to.
In piezoelectric materials or piezo elements, these atoms have opposite charges – one positive and the other negative. The moment these atoms of opposite charges get close together, they make electricity happen.
You can also do the opposite – apply an electric field on piezo elements to make their crystal structures bend, changing the material’s overall shape. When using a piezo speaker, you’re making the piezo element inside contract and expand so fast that it vibrates and makes a sound.
Also read: How to Control your Raspberry Pi through Windows via SSH
Using piezo speakers with the Raspberry Pi to generate sounds is as simple as making LEDs blink. You just need a few things, a different code, and won’t need a resistor.
If you’re having trouble looking for pin 7, hold your Raspberry Pi in a way that the GPIO pins are sticking to the right and then look at the GPIO pins. The top-left pin should be pin 1 and to its right is pin 2. Below pin 1 is pin 3 and to its right is pin 4 and so on.
Also read: How to Turn Your Raspberry Pi into a Video Conferencing Station
The code can look like a large mess at first glance, so let’s cut it up into three parts:
This isn’t a standardized grouping – I just made them up – but it’s always a good practice to divide your code into easily identifiable parts. It makes things easier when you’re trying to change any part of the code.
This is where you define which modules you’re “importing” into your code. The import commands here consist of two lines of code.
import RPi.GPIO as GPIO tells Python that you’re using the RPi.GPIO module to control the Raspberry Pi’s GPIO pins. as GPIO tells it that whenever you call the variable GPIO, you’re calling the RPi.GPIO module.
from time import sleep is another way of calling modules. But instead of taking the whole module, you’re just importing the sleep() function from the time module. This can help a lot when it comes to performance because Python won’t have to load the whole module; it just uses that one function.
Also read: How to Install Windows 11 on a Raspberry Pi 4
The code in the setup commands is where you “set up” or define all the important parts in your program, such as variables, settings, and pin designations. These only have to be defined once.
GPIO.setwarnings(False) prevents warnings from showing up when you run the code. Warnings still show up when your code runs successfully, but adding this piece of code keeps warning messages from flooding the terminal every time you enter python3 rpi-piezo.py. But this is more of a personal preference – you can just remove this bit if you want to see the warnings. It still works the same.
GPIO.setmode(GPIO.BOARD) tells Python how you want your Raspberry Pi’s general purpose input/output (GPIO) pins to be named. There are two ways: BOARD and BCM.
GPIO.setup(7, GPIO.OUT) tells Python that you’re using pin 7 as an output.
pin7 = GPIO.PWM(7, 100) makes a variable, pin7, that contains the string GPIO.PWM(7, 100). This shortens your code, so you can just use pin7 instead of calling GPIO.PWM(7, 100) all the time.
Lastly, pin7.start(50) sets pin 7 to PWM (Pulse Width Modulation) mode. This means that whenever pin 7 is set to HIGH, it emits 3.3V half of the time. The rest of the time, it doesn’t emit anything (or is at 0V).
Also read: ESP32 vs. Arduino Uno: Which One Should You Get?
Looped commands run on a loop – they repeat as long as you keep the script running. To do so, you have to keep them indented after while True:.
GPIO.output(7, GPIO.HIGH) turns pin 7 on HIGH. That pin is working and giving out a PWM signal. The function GPIO.output() takes in two parameters: the pin number and whether you want to set it HIGH or LOW. If you skip to the bottom part, you find GPIO.output(7, GPIO.LOW) which does the opposite – it turns pin 7 on LOW.
The lines of code in between are just a series of pin7.ChangeFrequency() and sleep(1). Adjusting their parameters lets you play different kinds of notes.
pin7.ChangeFrequency() is actually a shortcut form of GPIO.PWM(7, 100).ChangeFrequency(). Using the shortcut form makes it easier to change the pin you’re using. If you didn’t define pin7 = GPIO.PWM(7, 100) earlier, you have to change the pin number on every frequency change you make.
Also read: Raspberry Pi Monitor Not Working? Try These Fixes
What’s inside .ChangeFrequency() is the frequency of the PWM signal and, hence, the piezo element. Remember that a piezo element is just a solid crystal that slightly contracts when you pass electricity through it and relaxes when you stop. The rapid contracting and relaxing make sounds of varying pitches, and you can control the pitch by changing the number inside .ChangeFrequency(). To make things easier for you, there’s a comment after each pin7.ChangeFrequency() indicating what note they are.
Lastly, sleep(1) pauses the code for 1 second. If you pause the code after you change the frequency, you’d basically have yourself a single note – it’s gonna play that note for as long as you keep the code sleeping.
Also read: How to Program Arduino Through Visual Studio Code Using PlatformIO
So how does it all go, from a vibrating piezo element to sound, and then turn into something that could resemble music? Simple: it’s all about the frequency and pitch.
What we perceive as sounds with our ears are actually vibrations in the air. The more the air vibrates, the higher the sound’s pitch. We plot this out on paper as waves of varying patterns and give it an SI unit, i.e., a unit of measurement: Hz (which stands for Hertz). Sound waves with more Hz vibrate faster than those with less of it. We humans can hear sound waves vibrating somewhere between 20Hz and 20,000Hz.
When you used ChangeDutyCycle(), you changed the number of times that the piezo element would vibrate over time, i.e., the frequency. Hz is a measure of the frequency of vibrations in the air.
To change the sound in a way that at least resembles something like music, you have to change the frequency in a particular way. In other words, you have to modify the pitch. Unlike frequency, pitch is a measure of how high or low a sound sounds to our ears. By changing the pitch, you’re making something already close to music.
Of course, there is more to making music than just changing pitches. You also need pitch duration in there to make a note. And that’s where sleep() goes – you make the Raspberry Pi stay at a given pitch for a certain amount of time to give you a proper note!
Also read: How to Program an Arduino with a Raspberry Pi
Piezo speakers use a vibrating piezo element to produce sound. They are usually made of ceramic and are typically used in buzzers. Meanwhile, magnetic speakers use electromagnets that vibrate plastic membranes. They are used in smartphones and headsets.
Technically, yes. The piezo element inside piezo speakers bends one way if you apply voltage from one side, and the other way if you reverse it.
Just about anything that has something to do with pressure and vibration has piezo elements. This includes accelerometers, microphones, guitar pickups, and speakers. But there’s also one unusual thing that has them: lighters use them to make the spark that lights a flame.
Photos and screenshots by Terenz Jomar Dela Cruz
Our latest tutorials delivered straight to your inbox
How to Create a .Desktop File for Your Application in Linux
How to Cast Your Android Screen onto Your Linux Desktop
How to Fix 'No SIM Card Detected' Error on Android and iPhone
How to Copy and Paste Text, Files and Folders in Linux Terminal
How to Install Safari on Linux
How to Access an Android Phone With a Broken Screen
How to Set Up Bluetooth in Linux
How to Use Google Authenticator on a Windows PC
6 Ways to Check Hard Disk Health in Windows
How to Fix Mobile Data Not Working on Android
Affiliate Disclosure: Make Tech Easier may earn commission on products purchased through our links, which supports the work we do for our readers.
© 2022 Uqnic Network Pte Ltd. All rights reserved.