Skip to Content
This is the Beta version of our new Learning Paths approach. Please email feedback.

Buzzer

buzzer.ino
/* Project: Smart Home Component: Buzzer Sketch Description: This sketch has functions to sound and turn off the buzzer. Author: STEMVentor Educonsulting This code is copyrighted. Please do not reuse or share for any purpose other than for learning with subscribed STEMVentor programs. This code is for educational purposes only and is not for production use. */ // LIBRARIES // PIN DEFINTIONS // See board_parameters.h // GLOBAL CONSTANTS // See board_parameters.h // GLOBAL VARIABLES // INITIALIZE OBJECTS // LOCAL FUNCTIONS void buzzerSetup() { pinMode(BUZZER_PIN, OUTPUT); // Test the buzzer with a quick sound. soundBuzzerContinuous(1000, 3000); // (frequency in Hz, duration in milliseconds) delay(3*1000); soundBuzzerIntermittent(1000, 1*1000, 5*1000); if(OPERATING_MODE == 'D'){ Serial.println("Buzzer has been setup!"); } } void soundBuzzerContinuous(uint8_t frequency, unsigned long duration) { // // With some buzzers the tone() and noTone() functions do not work. // // You have to explicitly set the pin to HIGH or LOW to start or stop the buzzer. // // tone(pin, frequency in hz, duration in milliseconds) // tone(BUZZER_PIN, frequency, duration); // frequency defaults to 1 kHz (1000) // noTone(BUZZER_PIN); // This buzzer is active low which means it will sound on a low signal. // For an active high buzzer switch the signal order. digitalWrite(BUZZER_PIN, LOW); delay(duration); digitalWrite(BUZZER_PIN, HIGH); } void soundBuzzerIntermittent(uint8_t frequency, unsigned long pulse_time, unsigned long duration) { unsigned long buzzer_started = millis(); unsigned long buzzer_millis = millis(); while((buzzer_millis - buzzer_started) < duration){ // This buzzer is active low which means it will sound on a LOW signal. // For an active high buzzer switch the signal order. digitalWrite(BUZZER_PIN, LOW); delay(pulse_time); digitalWrite(BUZZER_PIN, HIGH); delay(pulse_time); buzzer_millis = millis(); } } void switchBuzzerOff(){ // This buzzer is active low which means it will go off on a HIGH signal. // For an active high buzzer pass LOW signal to turn off. digitalWrite(BUZZER_PIN, HIGH); }