In this task, you'll learn how to control an active buzzer using two handy functions: tone() to play a sound and noTone() to stop it.
Using the tone() function:
Using the noTone() function:
Example:
If your buzzer is connected to pin 8, you can do the following:
// Example using tone() and noTone()
int buzzPin = 8;
int dtOn = 1000;
int dtOff = 500;
int noteFreq = 1000;
void setup() {
// put your setup code here, to run once:
pinMode(buzzPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
tone(buzzPin, noteFreq);
delay(dtOn);
noTone(buzzPin);
delay(dtOff);
}
These functions let you create precise beeps, alerts, or even simple tunes. Try experimenting with different frequencies and durations!