I have built a circuit on my Arduino Mega 2560, with 8 LEDS plugged into digital ports 39, 41, 43, 45, 47, 49, 51, and 53. They are controlled by 8 Momentary Push Buttons plugged into digital ports 38, 40, 42, 44, 46, 48, 50, and 52. My code is as follows:
const int LED1 = 39;
const int LED2 = 41;
const int LED3 = 43;
const int LED4 = 45;
const int LED5 = 47;
const int LED6 = 49;
const int LED7 = 51;
const int LED8 = 53;
const int Button1 = 38;
const int Button2 = 40;
const int Button3 = 42;
const int Button4 = 44;
const int Button5 = 46;
const int Button6 = 48;
const int Button7 = 50;
const int Button8 = 52;
int CurrentButton[]={Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8};
int CB;
int CurrentLED[]={LED1,LED2,LED3,LED4,LED5,LED6,LED7,LED8};
int CL;
int count;
void setup(){
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
pinMode(LED5, OUTPUT);
pinMode(LED6, OUTPUT);
pinMode(LED7, OUTPUT);
pinMode(LED8, OUTPUT);
pinMode(Button1, INPUT);
pinMode(Button2, INPUT);
pinMode(Button3, INPUT);
pinMode(Button4, INPUT);
pinMode(Button5, INPUT);
pinMode(Button6, INPUT);
pinMode(Button7, INPUT);
pinMode(Button8, INPUT);
CB=CurrentButton[0];
CL=CurrentLED[0];
count=0;
}
void loop(){
for (count=0;count<8;count++) {
if (digitalRead(CB) == HIGH) {
digitalWrite(CL, LOW);
CB=CurrentButton[count];
CL=CurrentLED[count];
}
else {
digitalWrite(CL, HIGH);
}
}
}
My intended purpose was for each button to be corresponded to 1 LED (which worked), and for when each button was pressed its LED to turn off (this works) and the next in sequence to turn on (this doesn't work). While when an LED's corresponding button is pressed it does turn off, it isn't the next one in sequence, it is just a random other LED. I call it random because I have reset my arduino and while the first LED is always 1, the second LED to light up could be any of them.