// Define the pins
const int buttonPin = 12; // GPIO pin where the button is connected
const int relayPin = 14; // GPIO pin where the relay is connected
// Variables will change:
int buttonState = 0; // Variable for reading the pushbutton status
bool relayState = LOW; // Variable to store the relay state
void setup() {
// Initialize the relay pin as an output:
pinMode(relayPin, OUTPUT);
// Initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
// Start with the relay off
digitalWrite(relayPin, relayState);
// Initialize serial communication:
Serial.begin(115200);
}
void loop() {
// Read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// Check if the pushbutton is pressed.
// If it is, the buttonState is LOW:
if (buttonState == LOW) {
// Invert the relay state
relayState = !relayState;
// Update the relay state
digitalWrite(relayPin, relayState);
// Print the state to the serial monitor
if (relayState == HIGH) {
Serial.println("Relay is ON");
} else {
Serial.println("Relay is OFF");
}
// Wait for the button to be released
while (digitalRead(buttonPin) == LOW) {
delay(10);
}
}
// Small delay to avoid bouncing issues
delay(50);
}