Hello Arduiners, I'm making now an controller and I want to make LED lights when I push any button but I've got problem with more than 1 button. My code look like this
This one works corectly but when I make more buttons by this way effect look like this (when code is assigned to 2 buttons 1 (1 of 2 buttons make correct effect) lights corectly and 2nd like on photo, with all buttons (code assigned to all buttons) LED don't lights corectly but still lights like on picture):
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState6 = 0;
int buttonState7 = 0;
int buttonState8 = 0;
int buttonState9 = 0;
int buttonState10 = 0;
Local variables with the same names:
int buttonState2 = digitalRead(pushButton2);
int buttonState3 = digitalRead(pushButton3);
int buttonState4 = digitalRead(pushButton4);
int buttonState6 = digitalRead(pushButton6);
int buttonState7 = digitalRead(pushButton7);
int buttonState8 = digitalRead(pushButton8);
int buttonState9 = digitalRead(pushButton9);
int buttonState10 = digitalRead(pushButton10);
A REALLY bad idea.
if ((analogValue-lastAnalogValue) > 1 || (analogValue-lastAnalogValue) < -1) {
if (analogValue != lastAnalogValue) {
If the difference between the values is greater than one, there's not a snowball's chance in hell that they will then be equal.
Your piss-poor indenting makes your code hard to follow. There is a reason that the Tools menu has an Auto Format item. Learn what that reason is.
Instead of 8 switches, get rid of 6 of them. Get two working. Then, put the others back.
Using the internal pullup resistors is so much simpler. Connect one leg of the switch to ground. Connect the other leg to the pin. Turn on the internal pullup resistor by using INPUT_PULLUP in the pinMode statement. Then, LOW is pressed and HIGH is released, just like the top of the switch.
This code is a prime example for using arrays - whenever you have several similar/identical
things to process, use an array, then you only have to write the code once for all of them,
which also means fewer places for bugs and typos to creep in.