I’m want to do a changing led program with Arduino. When the program initiate all leds are off but when you press a button, the first led turn on, If you unpress the bottom the led go off. Then, if you press the button again the second led turn off and when yo unpress the button, it takes off. There are 8 leds and when you get the led number 8, the program will iniciate again. How can I do it?
int leds[] = {0,1,2,3,4,5,6,7};
int boton = 8;
int buttonPushCounter = -1;
int buttonState = 0;
int lastButtonState = 0;
int i = -1;
void setup () {
for (i=-1; i<=7;i++){
pinMode (leds[i],OUTPUT);
}
pinMode(boton, INPUT);
digitalWrite(boton,HIGH);
}
void loop () {
buttonState = digitalRead(boton);
if (buttonState != lastButtonState) {
if (buttonState == LOW) {
buttonPushCounter++;
digitalWrite(leds[buttonPushCounter], HIGH);
digitalWrite(leds[buttonPushCounter-1], LOW);
while(digitalRead(boton) == LOW) // when pin goes LOW
{
digitalWrite(buttonPushCounter, HIGH);
// turn on LED
}
digitalWrite(buttonPushCounter, LOW);
}
else {
Serial.println("off");
}
}
lastButtonState = buttonState;
if (buttonPushCounter % 8 == 0) {
digitalWrite(leds[0], HIGH);
buttonPushCounter = 0;
}
}
The else statement is crazy but the program works but it dont reset when it release the 8º led. Thanks you
As you had it the count could go to 8 then it would do the
digitalWrite(leds[buttonPushCounter], HIGH);
With the index of that array at 8 which is one bigger than the array was defined for. ( don’t forget that array indexes start at zero )
Note that you also use pins 0 and 1 for LEDs. These are best avoided as they are used for downloading code and putting an LED as a load on them might upset downloads.
The code run with and without the note but I think that if you divid contardorpulsos by 0 or 9 (when the variable realease 9), the condition (contadorpulsos % 9 == 0) come true. Thanks you for your supporting.
You are not understanding. The variable CAN NEVER reach the value of 9.
The line:-
contadorpulsos = (contadorpulsos + 1 ) & 0x07;
means the value can only reach 7.
See:- arduino.cc/en/Reference/BitwiseAnd
If you don't believe me then try printing out the value after the increment.
That's right. I add a code to show in serial port the variable and it don't realease 9. But, if you change: contadorpulsos = (contadorpulsos + 1 ) & 0x07; for: contadorpulsos++; it release 9 and, instantly, 0.