const int relay1 = 6; // Assuming relay1 is connected to pin 6
const int relay2 = 7;
const int relay3 = 8;
const int relay4 = 9;
const int button1 = 2; // Assuming button1 is connected to pin 2
const int button2 = 3;
const int button3 = 4;
const int button4 = 5;
// Variables to store the button states and relay states
int buttonState1 = 0;
int lastButtonState1 = 0;
int relayState1 = LOW;
int buttonState2 = 0;
int lastButtonState2 = 0;
int relayState2 = LOW;
int buttonState3 = 0;
int lastButtonState3 = 0;
int relayState3 = LOW;
int buttonState4 = 0;
int lastButtonState4 = 0;
int relayState4 = LOW;
void setup() {
// Initialize the button pins as inputs
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(button3, INPUT_PULLUP);
pinMode(button4, INPUT_PULLUP);
// Initialize the relay pins as outputs
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(relay3, OUTPUT);
pinMode(relay4, OUTPUT);
// Initially turn off all relays
digitalWrite(relay1, LOW);
digitalWrite(relay2, LOW);
digitalWrite(relay3, LOW);
digitalWrite(relay4, LOW);
}
void loop() {
// Read the state of the buttons
buttonState1 = digitalRead(button1);
buttonState2 = digitalRead(button2);
buttonState3 = digitalRead(button3);
buttonState4 = digitalRead(button4);
// Check if button 1 is pressed (state changed from HIGH to LOW)
if (buttonState1 == LOW && lastButtonState1 == HIGH) {
relayState1 = !relayState1; // Toggle relay state
digitalWrite(relay1, relayState1); // Update relay
}
lastButtonState1 = buttonState1; // Save the current state as last state
// Check if button 2 is pressed (state changed from HIGH to LOW)
if (buttonState2 == LOW && lastButtonState2 == HIGH) {
relayState2 = !relayState2; // Toggle relay state
digitalWrite(relay2, relayState2); // Update relay
}
lastButtonState2 = buttonState2; // Save the current state as last state
// Check if button 3 is pressed (state changed from HIGH to LOW)
if (buttonState3 == LOW && lastButtonState3 == HIGH) {
relayState3 = !relayState3; // Toggle relay state
digitalWrite(relay3, relayState3); // Update relay
}
lastButtonState3 = buttonState3; // Save the current state as last state
// Check if button 4 is pressed (state changed from HIGH to LOW)
if (buttonState4 == LOW && lastButtonState4 == HIGH) {
relayState4 = !relayState4; // Toggle relay state
digitalWrite(relay4, relayState4); // Update relay
}
lastButtonState4 = buttonState4; // Save the current state as last state
}