Fresh view - Simple L.E.D chaser

Hi all,

I have just started plying with my ardunio and have written the code below to make the 9 LED light up one at a time and along the line and then turn reverse the direction and count back down. I have checked my wiring using the "Blink" and checking each L.E.D, from doing this I can confirm the hardware appears good.

The problem I have is that the LED counts up to 8 and the does not light 9. It then counts back and 9 is dimly lite. I have looked at the code and I can get it to work with 4 LED's but going to 9 it goes wrong.

hopefully a fresh pair of eyes my point out where I am going wrong!!

Thanks in advanced.

// CODE FOR PROJECT 5
byte ledPin[] = {0,1,2,3,4,5,6,7,8}; //LED array for pins
int ledPin8 = OUTPUT;
int ledDelay(1000); //delay between led 
int direction = 1;
int currentLED = 0;
unsigned long changeTime;

void setup(){
  for (int x=0; x<8; x++) {
      pinMode(ledPin[x], OUTPUT);
    }
  changeTime = millis();
}

void loop(){
    if((millis() - changeTime) > ledDelay) {
      changeLED();
      changeTime = millis();
    }
}

void changeLED(){
  for(int x=0; x<8; x++){
    digitalWrite(ledPin[x], LOW);
  }
  digitalWrite(ledPin[currentLED],HIGH);
  currentLED += direction;
  if (currentLED ==8) {direction = -1;}
  if (currentLED ==0) {direction = 1;}
 }

There are nine entries in your array, but you iterate over only eight of them

for (int x=0; x<8; x++) { only goes from 0 to 7
change to for (int x=0; x<=8; x++) {
or for (int x=0; x<9; x++) {

:smiley: Thanks I couldn't see that for looking!!

Here's a good trick to do with this stuff.

byte ledPin[] = {0,1,2,3,4,5,6,7,8}; //LED array for pins
byte ledCount = sizeof(ledPin) / sizeof(ledPin[0]};  // calculates the number of elements in the array

// now use this in your for loops

for (int x=0; x < ledCount; x++)

With this approach you could add or remove a pin or two and not have to change any code to match. You can even use this value for the direction change.

By the way, using pins 0 and 1 is not the best idea. Those should be reserved for Serial's use, so you can debug the program.