How to Use Buzzer with Arduino: Simple Guide and Example
To use a buzzer with Arduino, connect the buzzer's positive pin to a digital pin (e.g.,
pin 8) and the negative pin to GND. Use the tone() function to play sounds and noTone() to stop them.Syntax
The main function to control a buzzer is tone(pin, frequency, duration). Here:
pin: Arduino digital pin connected to buzzer positive.frequency: Sound frequency in Hertz (Hz) to play.duration: Optional, how long to play the tone in milliseconds.
Use noTone(pin) to stop the buzzer sound on that pin.
arduino
tone(pin, frequency, duration); noTone(pin);
Example
This example plays a 1 kHz beep for half a second every second on pin 8.
arduino
const int buzzerPin = 8; void setup() { pinMode(buzzerPin, OUTPUT); } void loop() { tone(buzzerPin, 1000, 500); // Play 1000 Hz for 500 ms delay(1000); // Wait 1 second noTone(buzzerPin); // Stop sound delay(500); // Wait 0.5 second }
Output
The buzzer beeps once every second with a half-second sound.
Common Pitfalls
- Connecting buzzer pins incorrectly: positive to Arduino pin, negative to GND is required.
- Using
tone()withoutnoTone()can cause continuous sound. - Not setting the buzzer pin as
OUTPUTinsetup(). - Using a passive buzzer without
tone()will not produce sound.
arduino
/* Wrong: no pinMode set, no noTone used */ const int buzzerPin = 8; void loop() { tone(buzzerPin, 1000); // Plays tone continuously delay(1000); } /* Right: pinMode set, noTone used */ void setup() { pinMode(buzzerPin, OUTPUT); } void loop() { tone(buzzerPin, 1000, 500); delay(1000); noTone(buzzerPin); delay(500); }
Quick Reference
Buzzer Control Cheat Sheet:
tone(pin, freq, duration): Play sound at frequencyfreqHz fordurationms.noTone(pin): Stop sound onpin.- Connect buzzer + to Arduino pin, - to GND.
- Set buzzer pin as
OUTPUTinsetup().
Key Takeaways
Connect buzzer positive to Arduino digital pin and negative to GND.
Use tone(pin, frequency, duration) to play sounds on the buzzer.
Call noTone(pin) to stop the buzzer sound.
Always set the buzzer pin as OUTPUT in setup().
Passive buzzers need tone() to produce sound; active buzzers may only need HIGH/LOW signals.