Overview
tone(pin, frequency, duration) produces a square wave on any pin. A
passive buzzer or piezo disc turns it into sound at that pitch. An active
buzzer has its own oscillator and beeps at one fixed pitch whenever it gets power, so it cannot play
tunes.
You will need
- Arduino Uno R3
- Passive piezo buzzer
- Optional 100 Ω resistor in series to soften the volume
Wiring
| Uno pin | Connects to | Notes |
|---|---|---|
| 8 | Buzzer + (or either lead of a plain piezo) | |
| GND | Buzzer − |
The sketch
const int BUZZER_PIN = 8;
// C major scale, C4 to C5, in hertz
const int SCALE[] = {262, 294, 330, 349, 392, 440, 494, 523};
const int NOTE_COUNT = sizeof(SCALE) / sizeof(SCALE[0]);
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
for (int i = 0; i < NOTE_COUNT; i++) { // up
tone(BUZZER_PIN, SCALE[i], 250);
delay(300);
}
for (int i = NOTE_COUNT - 2; i >= 0; i--) { // back down
tone(BUZZER_PIN, SCALE[i], 250);
delay(300);
}
noTone(BUZZER_PIN);
delay(1500);
}How the code works
tone() returns immediately and the note plays in the background, so the
delay() sets the spacing between notes. Only one tone can play at a time. tone()
uses Timer2, which disables PWM on pins 3 and 11 while it runs. Magnetic (non-piezo) buzzers draw more
current and should be driven through a transistor.
What you should observe
- A scale plays up and back down, then a pause.
- A steady beep regardless of pitch: you have an active buzzer.