Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
1.4 Passive Buzzer
Introduction
In this project, we will learn how to make a passive buzzer play music by driving it with different frequencies. Passive buzzers, unlike active buzzers, require an external signal to produce sound.
What You’ll Need
To complete this project, you will need the following components:
COMPONENT |
PURCHASE LINK |
|---|---|
- |
|
Raspberry Pi |
- |
Circuit Diagram
The circuit uses a passive buzzer, a NPN transistor, and a 1kΩ resistor. The resistor protects the transistor from excessive current. By varying the frequency of the GPIO pin connected to the transistor, the buzzer produces different sounds, enabling it to play music.
Wiring Diagram
Follow these steps to build the circuit:
Connect the base of the NPN transistor to PWM0 through the resistor.
Connect the emitter of the transistor to the power supply (+).
Connect the collector of the transistor to one terminal of the passive buzzer.
Connect the other terminal of the buzzer to the ground (-).
Running the Example
All example code used in this tutorial is available in the ai-lab-kit directory.
Follow these steps to run the example:
cd ~/ai-lab-kit/python/
sudo python3 1.4_PassiveBuzzer.py
After running the script, the passive buzzer plays a short musical tune through PWM 0. Each note is played in sequence for its set duration, and the current note is printed to the console as it plays. When the tune finishes, the buzzer stops automatically, with silent pauses where the note is None. You can also stop the program at any time by pressing Ctrl + C.
Code
The following Python code generates musical notes using a passive buzzer:
#!/usr/bin/env python3
from fusion_hat.modules import Buzzer
from fusion_hat.pwm import PWM
from time import sleep
# Initialize a TonalBuzzer connected to PWM 0
tb = Buzzer(PWM('P0')) # Update this pin number based on your setup
def play(tune):
"""
Play a musical tune using the buzzer.
:param tune: List of tuples (note, duration), where each tuple represents a note and its duration.
"""
for note, duration in tune:
print(note) # Output the current note being played
tb.play(note,float(duration)) # Play the note on the buzzer
tb.off() # Stop playing after the tune is complete
# Define a musical tune as a sequence of notes and durations
tune = [('C#4', 0.2), ('D4', 0.2), (None, 0.2),
('Eb4', 0.2), ('E4', 0.2), (None, 0.6),
('F#4', 0.2), ('G4', 0.2), (None, 0.6),
('Eb4', 0.2), ('E4', 0.2), (None, 0.2),
('F#4', 0.2), ('G4', 0.2), (None, 0.2),
('C4', 0.2), ('B4', 0.2), (None, 0.2),
('F#4', 0.2), ('G4', 0.2), (None, 0.2),
('B4', 0.2), ('Bb4', 0.5), (None, 0.6),
('A4', 0.2), ('G4', 0.2), ('E4', 0.2),
('D4', 0.2), ('E4', 0.2)]
try:
play(tune) # Execute the play function to start playing the tune
except KeyboardInterrupt:
# Handle KeyboardInterrupt for graceful termination
pass
This Python script plays a musical tune using a passive buzzer connected to PWM 0. When executed:
The script iterates through a predefined sequence of musical notes (
tune), playing each note for a specified duration.The notes are output to the console as they are played, providing a visual reference.
The tune stops automatically once all notes are played. The buzzer produces no sound during pauses (when the note is
None).The program can be interrupted gracefully using
Ctrl+C.
Understanding the Code
Library Import
The
Buzzerclass from thefusion_hatlibrary is used to generate tones, andtime.sleepintroduces delays for note durations.from fusion_hat.modules import Buzzer from fusion_hat.pwm import PWM from time import sleep
Buzzer Initialization
The
Buzzeris associated with PWM0 for tone generation.# Initialize a TonalBuzzer connected to PWM 0 tb = Buzzer(PWM('P0')) # Update this pin number based on your setup
Playing Notes
The
playfunction iterates over a list of tuples representing musical notes and their durations. Each note is played for its specified duration, followed by a brief stop.def play(tune): for note, duration in tune: print(note) # Output the current note being played tb.play(note,float(duration)) # Play the note on the buzzer tb.off() # Stop playing after the tune is complete
Tune Definition
The
tunevariable contains a sequence of notes (e.g., ‘C#4’) and durations (e.g., 0.2 seconds).tune = [ ('C#4', 0.2), ('D4', 0.2), (None, 0.2), ('Eb4', 0.2), ('E4', 0.2), (None, 0.6), ('F#4', 0.2), ('G4', 0.2), (None, 0.6), ('Eb4', 0.2), ('E4', 0.2), (None, 0.2), ('F#4', 0.2), ('G4', 0.2), (None, 0.2), ('C4', 0.2), ('B4', 0.2), (None, 0.2), ('F#4', 0.2), ('G4', 0.2), (None, 0.2), ('B4', 0.2), ('Bb4', 0.5), (None, 0.6), ('A4', 0.2), ('G4', 0.2), ('E4', 0.2), ('D4', 0.2), ('E4', 0.2) ]
Keyboard Interrupt Handling
The
try-exceptblock ensures the program stops gracefully when interrupted (e.g., Ctrl+C).try: play(tune) except KeyboardInterrupt: pass
Troubleshooting
No Sound from the Buzzer
Cause: Incorrect GPIO pin connection or incompatible buzzer type.
Solution: Ensure the TonalBuzzer is connected to PWM 0.
Intermittent or Stuttering Sound
Cause: Timing inconsistencies in the
sleep()function.Solution: Confirm that the durations in the
tunelist are appropriately calibrated for smooth transitions.
Extendable Ideas
Custom Tunes
Allow the user to input their own sequence of notes and durations:
user_tune = [] while True: note = input("Enter a note (or 'stop' to finish): ") if note.lower() == 'stop': break duration = float(input("Enter duration for the note: ")) user_tune.append((note, duration)) play(user_tune)
Multiple Tunes
Add predefined tunes and let the user select which one to play:
tunes = { "tune1": [('C4', 0.5), ('D4', 0.5), (None, 0.5)], "tune2": [('G4', 0.3), ('A4', 0.3), (None, 0.3)] } choice = input("Choose a tune (tune1/tune2): ") play(tunes[choice])
Real-Time Interaction
Use buttons or a keyboard to play notes interactively, turning the buzzer into a simple instrument.
Chained Tunes
Automatically chain multiple tunes together to create a longer piece.
Dynamic Speed Adjustment
Allow users to change the playback speed dynamically by modifying the note durations:
speed_factor = float(input("Enter speed factor (e.g., 1.0 for normal, 0.5 for faster): ")) adjusted_tune = [(note, duration * speed_factor) for note, duration in tune] play(adjusted_tune)
Conclusion
This project demonstrates how to use a passive buzzer to play musical notes. By combining hardware and software, you can create a variety of sounds and melodies for interactive projects.