/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-button-toggle-relay
*/
#define BUTTON_PIN 27 // ESP32 pin GIOP22 connected to button's pin
#define RELAY_PIN 26 // ESP32 pin GIOP27 connected to relay's pin
#define BUZZER_PIN 5 // ESP32 pin GIOP27 connected to relay's pin
int last_button_state = HIGH;
int last_relay_state = LOW;
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(RELAY_PIN, OUTPUT); // set ESP32 pin to output mode
pinMode(BUZZER_PIN, OUTPUT); // set ESP32 pin to output mode
}
void loop() {
int button_state = digitalRead(BUTTON_PIN);
int relay_state = digitalRead(RELAY_PIN);
last_relay_state = relay_state;
if (button_state != last_button_state) {
last_button_state = button_state;
if (last_button_state == LOW) {
Serial.println("The button is pressed");
// control relay arccoding to the toggled state
digitalWrite(RELAY_PIN, !relay_state);
delay(5000);
}
Serial.println("Desligando relé");
// control relay arccoding to the toggled state
digitalWrite(RELAY_PIN, LOW);
button_state = digitalRead(BUTTON_PIN);
if (button_state == LOW) {
Serial.println("Permaneceu ligado demais");
myTone(BUZZER_PIN);
}
if (last_button_state == HIGH) {
Serial.println("Desligando buzzer");
myNoTone(BUZZER_PIN);
}
}
}
void myTone( int pin)
{
ledcAttachPin(pin, 0); // pin, channel
ledcWriteNote(0, NOTE_F, 4); // channel, frequency, octave
}
void myNoTone( int pin)
{
ledcDetachPin(pin);
}