Introduction
A passive buzzer can be used to produce various tones and melodies by varying the frequency of the signal sent to it. In this experiment, we demonstrate how to generate a simple melody using an Arduino and a buzzer.
Components Needed
- Arduino (e.g., Uno, Nano)
- Passive buzzer module
- Resistor (220Ω, optional for current limiting)
- Breadboard and jumper wires
Circuit Setup
Connect the buzzer to the Arduino as follows:
- Connect the positive terminal of the buzzer to Arduino pin 8.
- Connect the negative terminal of the buzzer to Arduino GND (via a 220Ω resistor, if needed).
Note: If you're unsure about your buzzer type, test its polarity before connecting.
Code for Buzzer Melody
Upload the following code to your Arduino to play a melody:
// Define pin for the buzzer
#define BUZZER_PIN 8
// Define melody notes using their frequencies (in Hz)
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_B4 494
#define NOTE_C5 523
// Melody and duration arrays
int melody[] = {NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5};
int durations[] = {500, 500, 500, 500, 500, 500, 500, 500}; // All notes 500 ms
void setup() {
pinMode(BUZZER_PIN, OUTPUT); // Set buzzer pin as output
}
void loop() {
// Play the melody
for (int i = 0; i < 8; i++) {
tone(BUZZER_PIN, melody[i], durations[i]); // Play note
delay(durations[i] * 1.3); // Wait for note duration (slightly longer)
noTone(BUZZER_PIN); // Stop the tone before the next note
}
delay(2000); // Pause before repeating melody
}
Explanation
tone()
: Generates a square wave at the specified frequency for the given duration.noTone()
: Stops the tone being played.melody[]
: Contains the notes for the melody, defined by their frequencies in Hz.durations[]
: Defines the duration (in milliseconds) of each note in the melody.
Applications of Buzzers
Buzzers are commonly used in:
- Alarm and notification systems
- Simple musical projects
- User interface feedback (e.g., button presses)
Troubleshooting
- If no sound is heard, ensure the buzzer is connected to the correct pin and polarity.
- If the melody sounds distorted, verify the resistor value and ensure the buzzer is a passive type.
- Use
tone()
with varying frequencies to test the buzzer functionality.