Program only runs for a short time

Hi, I’m 67 and trying to learn Arduino. This program switches 4 LED’s in sequence. It runs but only for a short time. I have tried replacing ledArray with ledPin with similar but different behaviour. Any help would be appreciated as it’s keeping me awake at night and at my age I need my beauty sleep.
Bruce P
// Define variables here first

int ledPin[4] = {6,7,8,9}; // 4 LED’s connected
int ledDelay = 200;

void setup() {
// put your setup code here, to run once:
for(int i = 0; i < ledPin ; i++) // this i is the number of elements in the array
{
pinMode (ledPin[i], OUTPUT);
}
}

void loop()
// put your main code here, to run repeatedly:
{
for(int i = 0; i < 5; i++){
digitalWrite(ledPin[i], HIGH);
delay (ledDelay);
digitalWrite(ledPin[i], LOW);

}
for (int i = 4; i > 0; i–){
digitalWrite(ledPin[i], HIGH);
delay (ledDelay);
digitalWrite(ledPin[i], LOW);
//delay (ledDelay); // to make it look pretty
}
}

Hi Bruce,

Welcome to the club :wink:

Looks like you’ve got a bit of reading to do to get your code working. Core have a good bit on Arrays and pointers here: https://core-electronics.com.au/tutorials/c-programming-for-makers.html#ch5

Your setup() loop will run for an undefined length of time because ledPin will be some random memory address (like a house/street number). You want the number of rooms in the house not the number of the house at ledPin. For that you need to look into the sizeOf() function.

Regarding your loop(), you’re going to be looking into rooms in the house next door, so weird things will happen. Arrays in C++ are zero indexed meaning you start counting from zero. Your array will go from ledPin[0]=6 to ledPin[3]=9. You’re trying to access ledPin[4] which is uncharted territory. You can do this and the compiler won’t stop you, you’ll just get weird behaviour.

Hello Oliver,
Thank you very much for your comprehensive reply.
As you said, I have a lot of reading to do.
I’m finding that there are many ways to achieve the same result but as a newbie this can be confusing as it can look like something different when it’s just a different approach.
I’m sure we will talk again.
:slight_smile:
Bruce(67)

2 Likes