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.
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.
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.
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.