Passive Buzzer

A passive buzzer requires an external signal to create sound. It does not have a built-in oscillator, so it relies on a square wave signal or frequency input from the microcontroller to produce sound.

To produce different tones with a passive buzzer using the ESP32, you can generate varying frequencies using the tone() function, which takes the frequency as a parameter. Different frequencies correspond to different musical notes or pitches. By altering the frequency, you can control the pitch of the sound produced by the buzzer.

#define BUZZER_PIN 23 // Pin for passive buzzer

// Define some musical notes' frequencies (in Hz)
#define NOTEC4 261 // C4 (Middle C)
#define NOTED4 294 // D4
#define NOTEE4 329 // E4
#define NOTEF4 349 // F4
#define NOTEG4 392 // G4
#define NOTEA4 440 // A4
#define NOTEB4 466 // B4


void setup() {
    pinMode(BUZZER_PIN, OUTPUT); // Set the buzzer pin as output
}


void loop() {

    // Play some musical notes with delays
    tone(BUZZER_PIN, NOTEC4); // Play C4
    delay(500);
    tone(BUZZER_PIN, NOTED4); // Play D4
    delay(500);
    tone(BUZZER_PIN, NOTEE4); // Play E4
    delay(500);
    tone(BUZZER_PIN, NOTEF4); // Play F4
    delay(500);
    tone(BUZZER_PIN, NOTEG4); // Play G4
    delay(500);
    tone(BUZZER_PIN, NOTEA4); // Play A4
    delay(500);
    tone(BUZZER_PIN, NOTEB4); // Play B4
    delay(500);

    // Stop the tone for a moment before repeating
    noTone(BUZZER_PIN);
    delay(1000);

}
C++
#define NOTEA4 440
C++

This defines a preprocessor macro named NOTEA4 and assigns it the value 440. It represents the frequency (in Hertz) of the musical note A4, which is 440 Hz. By using a macro like NOTEA4, the code becomes more readable and self-explanatory. Instead of writing 440, you can use the musical note name directly in your code.

tone(BUZZER_PIN, NOTEA4);
C++

This generates a square wave at the frequency specified by NOTEA4 (440 Hz in this case) on the pin defined by BUZZER_PIN (e.g., pin 23). The tone() function works by setting up a timer to toggle the pin between HIGH and LOW states at the frequency you provide (in this case, 440 Hz). This toggling creates a square wave that drives the passive buzzer.

noTone(BUZZER_PIN);
C++

Stops the tone generation on the specified pin (BUZZER_PIN). This effectively silences the passive buzzer. The noTone() function disables the timer and stops toggling the pin, leaving the pin in a LOW state.

RELATED ARTICLES