// Pin definitions
const int potPin = A0; // Analog pin for potentiometer
const int relayPin1 = 2; // Digital pin for the first relay module
const int relayPin2 = 8; // Digital pin for the second relay module
const int button1Pin = 3; // Digital pin for button 1
const int button2Pin = 4; // Digital pin for button 2
const int button3Pin = 5; // Digital pin for button 3
// Variables to store the previous state of each button
int button1State = HIGH;
int button2State = HIGH;
int button3State = HIGH;
// Variables for toggle functionality
bool toggleActive = false;
unsigned long toggleStartTime = 0;
int interval = 0; // Initial interval value
void setup() {
pinMode(potPin, INPUT);
pinMode(relayPin1, OUTPUT);
pinMode(relayPin2, OUTPUT);
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
pinMode(button3Pin, INPUT_PULLUP);
}
void loop() {
// Read potentiometer value
int potValue = analogRead(potPin);
// Map potentiometer value (0-1023) to time interval (100-2000 ms)
interval = map(potValue, 0, 1023, 100, 2000);
// Check button states
if (buttonStateChanged(button1Pin, &button1State)) {
toggleActive = false;
digitalWrite(relayPin1, LOW);
digitalWrite(relayPin2, LOW); // Turn off the second relay
} else if (buttonStateChanged(button2Pin, &button2State)) {
toggleActive = false;
digitalWrite(relayPin1, HIGH);
digitalWrite(relayPin2, HIGH); // Turn on the second relay
} else if (buttonStateChanged(button3Pin, &button3State)) {
toggleActive = true;
toggleStartTime = millis();
}
// Toggle functionality
if (toggleActive) {
if (millis() - toggleStartTime >= interval) {
digitalWrite(relayPin1, !digitalRead(relayPin1)); // Toggle relay state
digitalWrite(relayPin2, digitalRead(relayPin1)); // Mirror the state on the second relay
toggleStartTime = millis(); // Reset toggle timer
}
}
}
// Function to check button state change
bool buttonStateChanged(int pin, int *lastState) {
int currentState = digitalRead(pin);
if (currentState != *lastState) {
delay(50); // Debounce delay
currentState = digitalRead(pin);
if (currentState != *lastState) {
*lastState = currentState;
return currentState == LOW;
}
}
return false;
}