I am trying to write code that performs the following: When I press a button (Pin2) the first time, I want Relay 1 on the Arduino relay shield to close for 1 second, and Relay 2 to latch on.
On the second press of the button, I want both relays to turn off. (Repeating this sequence)
When I press the button the first time, Relay 1 Turns on, then off, then on and off again. (Don't know where the other "ON-OFF" is coming from. Relay 2 does latch on.
When I press the button again, it repeats. I believe the "IF" statement may have an error. I'm using "RlyState" through the IF statement to determine when IF or ELSE is used.
Obviously, I am new to coding. Any assistance would be most appreciated. (I also used the example in Arduino IDE for debouncing) The code is below...
/*
Sketch will be used to initiate Raspberry with a momentary 1 second output to Relay1 and a latching output to Relay 2
for the my Arcade
Pins are 4,7,8, & 12 for the 4 relays
*/
const int pButton = 2; //Number of the pushbutton pin
const int Rly1 = 4; // Pin number for Relay 1 Raspberry
const int Rly2 = 7; // Pin number for relay 2 LED Latch
int buttonState = 0; // Variable for reading the pushbutton status
int RlyState = 0; // The current state of the output pin
int lastButtonState = 0; // The current reading of the input pin
long lastDebounceTime = 0; //The last time the output pin was toggled
long dBounceDelay = 50; // the debounce time, increase if chatters
void setup() {
pinMode(pButton, INPUT); //Initialize the Pbutton pin as an Input
pinMode(Rly1, OUTPUT); // Initialize Relay 1 pin as an Output
pinMode(Rly2, OUTPUT); //Initialize Relay 2 pin as an Output
Serial.begin(9600);
}
void loop() {
int reading = digitalRead(pButton); // Read the state of the Pushbutton Pin
// Check if the Pushbutton is pressed
Serial.print("Button State is ");
Serial.println(buttonState);
Serial.print("RlyState is ");
Serial.println(RlyState);
Serial.print("reading is ");
Serial.println(reading);
delay(400);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > dBounceDelay) {
buttonState = reading;
}
digitalWrite(Rly1, buttonState);
lastButtonState = reading;
if (buttonState == HIGH && RlyState == LOW) {
digitalWrite (Rly1, HIGH);
delay(1000);
digitalWrite (Rly1, LOW);
digitalWrite (Rly2, HIGH);
digitalWrite (RlyState, HIGH);
}
else {
if (buttonState == HIGH && RlyState == HIGH) {
digitalWrite (Rly1, LOW);
digitalWrite (Rly2, LOW);
digitalWrite (RlyState, LOW);
}
}
}