// Pin Definitions
const int relayPin = 8; // Relay control pin
const int buttonPin = 2; // Push button pin
const int ledStatePin = 13; // Optional: LED to show relay state
// Variables to hold the button state and the relay state
int buttonState = 0;
int relayState = LOW;
void setup() {
// Set relay and button pin modes
pinMode(relayPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Enable internal pull-up resistor
pinMode(ledStatePin, OUTPUT); // Optional LED for visual relay state feedback
// Start serial for debugging
Serial.begin(9600);
// Start with the relay off
digitalWrite(relayPin, LOW);
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Print button state to serial monitor
//Serial.print("Button State: ");
//Serial.println(buttonState);
// If button is pressed (active low logic)
if (buttonState == HIGH) {
// Toggle the relay state
relayState = !relayState;
digitalWrite(relayPin, LOW);
digitalWrite(relayPin, relayState);
delay(1000);
// Optional: turn on/off an LED for visual feedback
digitalWrite(ledStatePin, relayState);
// Wait for a while to debounce the button
delay(200);
}
}