Basically, I have 2 tactile buttons on a breadboard and a Sunfounder 8 relay board. In the code, the button associated with ledState works, and triggers relay 1 (ledPin) on and off. However, the 2nd button will not turn relay2 on and off. Using the serial monitor, I can see that the Uno see the button go low when I press it, but I can't seem to get it to trigger the 2nd relay. Any help would be appreciated!
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int button2Pin = 4; //pb 2
const int ledPin = 12; // the number of the LED pin
const int relay2 = 8;// Variables will change:
int ledState = HIGH; // the current state of the output pin
int relayState = LOW;
int buttonState; // the current reading from the input pin
int button2State;
int lastButton2State = LOW;
int lastButtonState = LOW; // the previous reading from the input pin// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickersvoid setup() {
pinMode(buttonPin, INPUT);
pinMode(button2Pin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(relay2, OUTPUT);// set initial LED state
digitalWrite(ledPin, ledState);
digitalWrite(relay2, relayState);
}void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
int reading2 = digitalRead(button2Pin);// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}if (reading2 != lastButton2State) {
lastDebounceTime = millis();
}if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:if (reading2 != button2State) {
button2State = reading2;
}// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}if (button2State == HIGH) {
button2State = !relayState;
}
}
}// set the LED:
digitalWrite(ledPin, ledState);
digitalWrite(relay2, relayState);// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = reading;
lastButton2State = reading2;
}