Needed Components with eBay Links
- Arduino Nano
- Piezo Buzzer
- 220Ω Resistor (optional for current limiting)
- Breadboard
- Jumper Cables
- Micro USB Cable Red
Understanding the Buzzer
A buzzer is a simple device that makes a sound when a voltage is applied. Active buzzers will sound continuously when powered, while passive buzzers need specific frequencies to produce sound (these can be controlled with the Arduino using PWM).
Key Functions
digitalWrite(pin, value)
: Turns a pin on (HIGH) or off (LOW).tone(pin, frequency, duration)
: Plays a tone at the specified frequency on a pin.noTone(pin)
: Stops the tone playing on a specific pin.
Wiring the Circuit
Connect the buzzer to your Arduino as follows:
- One pin of the buzzer to digital pin 9 on the Arduino.
- The other pin of the buzzer to GND on the Arduino (you may add a 220Ω resistor in series).
Arduino Code for Controlling a Buzzer
This code will make the buzzer beep continuously:
// Buzzer Control
int buzzerPin = 9; // Pin connected to the buzzer
void setup() {
pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as an output
}
void loop() {
digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
delay(1000); // Wait for 1 second
digitalWrite(buzzerPin, LOW); // Turn off the buzzer
delay(1000); // Wait for 1 second
}
Controlling Buzzer Tones
If you're using a passive buzzer, you can control the tone with different frequencies. Try the following code to play a series of tones:
// Buzzer with Tones
int buzzerPin = 9; // Pin connected to the buzzer
void setup() {
pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as an output
}
void loop() {
tone(buzzerPin, 1000, 500); // Play 1kHz tone for 500 ms
delay(1000); // Wait for 1 second
tone(buzzerPin, 1500, 500); // Play 1.5kHz tone for 500 ms
delay(1000); // Wait for 1 second
}
Upload & Test
- Connect your Arduino to your computer using a USB cable.
- Open the Arduino IDE and copy the code above into the editor.
- Select your board and the correct port in the IDE.
- Upload the code by clicking the upload button.
- The buzzer should now beep on and off or produce tones depending on which code you uploaded.
Code Breakdown
For continuous buzzing, we use digitalWrite()
to send a HIGH or LOW signal to the buzzer. For tone control, we use the tone()
function to generate a sound at a specific frequency. The frequency is in hertz (Hz), and the duration is in milliseconds.
Conclusion
This experiment demonstrates how to control a buzzer using digital pins on the Arduino. Whether you’re looking to create a basic alert system or generate specific sounds, this project serves as a great introduction to sound control with Arduino.