i want to control a relay module using a switch button but my code seems to always have something wrong, everytime i upload it the relay gets activated automatically and arduino is not reading the switch.
there are 3 switches where eachs controls activates the relay in a different sequence that makes a buzzer buzz in that sequence
the switch also is a 3 pin switch fyi
const int SWITCH_1_PIN = 2;
const int SWITCH_2_PIN = 3;
const int SWITCH_3_PIN = 4;
const int RELAY_PIN = 5;
// Define states for each switch
enum SwitchState {
OFF,
SWITCH_1_ON,
SWITCH_2_ON,
SWITCH_3_ON
};
SwitchState switchState = OFF;
unsigned long relayStartTime = 0;
// Function declaration
void handleSwitch(int switchPin, SwitchState switchOnState, unsigned long onDuration, unsigned long offDuration, unsigned long onDuration2, unsigned long loopDuration);
void setup() {
Serial.begin(9600); // Initialize serial communication
Serial.println("Program starting...");
pinMode(SWITCH_1_PIN, INPUT_PULLUP);
pinMode(SWITCH_2_PIN, INPUT_PULLUP);
pinMode(SWITCH_3_PIN, INPUT_PULLUP);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, HIGH); // Initially turn off the relay
}
void loop() {
handleSwitch(SWITCH_1_PIN, SWITCH_1_ON, 5000, 115000, 0, 120000);
handleSwitch(SWITCH_2_PIN, SWITCH_2_ON, 5000, 1000, 1000, 114000);
handleSwitch(SWITCH_3_PIN, SWITCH_3_ON, 1000, 4000, 5000, 109000);
}
void handleSwitch(int switchPin, SwitchState switchOnState, unsigned long onDuration, unsigned long offDuration, unsigned long onDuration2, unsigned long loopDuration) {
if (digitalRead(switchPin) == LOW) {
if (switchState == OFF) {
// Switch is turned ON
switchState = switchOnState;
relayStartTime = millis();
digitalWrite(RELAY_PIN, LOW); // Activate the relay
}
} else {
// Switch is turned OFF
if (switchState != OFF) {
digitalWrite(RELAY_PIN, HIGH); // Deactivate the relay
switchState = OFF;
}
}
// Check if it's time to loop (considering off time)
if (millis() - relayStartTime >= loopDuration) {
relayStartTime = millis();
digitalWrite(RELAY_PIN, LOW); // Activate the relay
switchState = switchOnState;
}
}