/* MainsOffDetector.ino (c)2025 Forward Computing and Control Pty. Ltd. NSW Australia, www.forward.com.au This code is not warranted to be fit for any purpose. You may only use it at your own risk. This generated code may be freely used for both private and commercial use provided this copyright is maintained. */ /** This sketch check if the Main AC is still available. If not it sounds a buzzer. The push button cancels the buzzer after which the buzzer will not sound again until the Mains is restored and is then lost again Restoring mains power also cancels the buzzer. The sketch is compiled on a DFROBOT Firebeetle 2 ESP32-C6 using ESP32 board support V3.3.0 (V3.3.3 has some compile errors in its code) **/ #include "DebouncedSwitch.h" const int mainsDetectionPin = 7; DebouncedSwitch mainsDetectorSw(mainsDetectionPin); // monitor a switch on input bool mainsOn = false; const int buzzerPin = 9; const int switchPin = 8; const int switchPinGND = 1; // provides a separate GND pin for the pushbutton DebouncedSwitch sw(switchPin); // monitor a switch on input // initial buzzer void initBuzzer() { pinMode(buzzerPin, OUTPUT); digitalWrite(buzzerPin, LOW); } // turn buzzer on void turnBuzzerOn() { digitalWrite(buzzerPin, HIGH); } // turn buzzer off void turnBuzzerOff() { digitalWrite(buzzerPin, LOW); } // called every loop void checkForMainsFailure() { mainsDetectorSw.update(); if (mainsDetectorSw.isChanged()) { if (mainsDetectorSw.isDown()) { // was high and now low so lost mains turnBuzzerOn(); } } if(!mainsDetectorSw.isDown()) { turnBuzzerOff(); // mains restored cancel buzzer } } void setup() { // Serial.begin(115200); // for (int i = 10; i > 0; i--) { // delay(500); // Serial.print(i); // Serial.print(' '); // } // Serial.println(); pinMode(switchPinGND, OUTPUT); digitalWrite(switchPinGND, LOW); // provide a GND for the switch initBuzzer(); mainsOn = false; } void loop() { checkForMainsFailure(); sw.update(); // call this every loop to update switch state if (sw.isDown()) { // debounced switch is down, cancel buzzer turnBuzzerOff(); } }