Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.
int button_prev = 0;
int button = 0;
void loop(){
button_prev = button;
button = digitalRead(12);
if (button_prev != button) {
digitalWrite(act_pin[j], HIGH);
j = (j+1) % 5;
}
}
I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on. But I don't see where the behavior of j comes from...
[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]
[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.
But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button.
Serial.println
as well just spits out one character, similiar looking to a d
.]
Can anyone point out my mistake to me?
This is the circuit
and this is the old code of the sketch
int act_pin[6] = {A0, A1, A2, A3, A4};
int j = 0;
void setup(){
Serial.begin(9600);
for (int k = 0; k < 5; k++) {
pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output
digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off
pinMode(12, INPUT); //sets pin connected to button as input
}
}
void loop(){
char button = {digitalRead(12)}; //stores if the button was pressed
Serial.println(button);
if(button == HIGH){
digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press
j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4
button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
}
}