This is part of a larger project (Hot Tub Controller) that I am working on and I am starting with the basics. The buttons.
I used to do a lot more with the Arduino about 4-5 years ago and have not picked it back up till about a few months ago.
I am wanting to control relays with 4 push buttons. Below code kind of works, but mostly keeps the relays/leds on. If you hold one button and press the others it will turn off. Push buttons are soldered as pull up. using a Uno R3
const int Button_1 = 9;
const int Button_2 = 8;
const int Button_3 = 7;
const int Button_4 = 6;
int buttonState_1 = 0;
int lastbuttonState_1 = 0;
int buttonState_2 = 0;
int lastbuttonState_2 = 0;
int buttonState_3 = 0;
int lastbuttonState_3 = 0;
int buttonState_4 = 0;
int lastbuttonState_4 = 0;
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 4;
const int ledPin4 = 5;
void setup(){
//INPUT PINS
pinMode(Button_1, INPUT);
pinMode(Button_2, INPUT);
pinMode(Button_3, INPUT);
pinMode(Button_4, INPUT);
//OUTPUT PINS
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
}
void loop(){
if (buttonState_1 = digitalRead(Button_1)){
(buttonState_1 == HIGH);
digitalWrite(ledPin1, HIGH);
lastbuttonState_1 = buttonState_1;
}
if (buttonState_2 = digitalRead(Button_2)){
(buttonState_2 == HIGH);
digitalWrite(ledPin2, HIGH);
lastbuttonState_2 = buttonState_2;
}
if (buttonState_3 = digitalRead(Button_3)){
(buttonState_3 == HIGH);
digitalWrite(ledPin3, HIGH);
lastbuttonState_3 = buttonState_3;
}
if (buttonState_4 = digitalRead(Button_4)){
(buttonState_4 == HIGH);
digitalWrite(ledPin4, HIGH);
lastbuttonState_4 = buttonState_4;
}
else {
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
delay(50);
}
Is the behaviour of your sketch as you have described it the desired behaviour ?
Substituting the leds (which I guess you have from the pin numbering) with relay modules, suitably powered, should be quite straightforward.
Picture attached of the Layout for testing. The 4 channel relay came in yesterday so I can start using that instead of the LEDs. I was trying to modify the change state example at first and with suggestions it looks like it is getting closer.