# I'm trying to understand code

Hello everyone, i'm new to this and i found this code :

``````int led[] = {1, 2, 3, 4, 5, 6, 7, 8};
int led_pin;
void setup() {
led_pin = sizeof(led) / sizeof(int);
for (int i = 0; i <= led_pin; i++) {
pinMode(led[i], OUTPUT);
}
}
void loop() {
s2m();  //
}
//
void s2m() {
for (int i = 0; i < led_pin / 2; i++) {
digitalWrite(led[i], HIGH);
digitalWrite(led[led_pin - 1 - i], HIGH);
delay(200);
digitalWrite(led[i], LOW);
digitalWrite(led[led_pin - 1 - i], LOW);
}
}
``````

Can you help me explain this? Thank you so much!

``````int led[] = {1, 2, 3, 4, 5, 6, 7, 8}; // A list of pin numbers.

int led_pin; // Total number of pins

// Setup - runs once.
void setup()
{
// Calculate the number of pins
led_pin = sizeof(led) / sizeof(int);

// Loop through each of the pins.
for (int i = 0; i <= led_pin; i++) // This looks wrong - should be < led_pin
{
// Define the pin as an output pin.
pinMode(led[i], OUTPUT);
}
}

// Loop - runs continually.
void loop()
{
// Call subroutine to flash LEDs
s2m();
}

// Routine that flashes LEDs in pairs, starting with the outer LEDs first, and moving inwards.
// 1st loop - pins 1 & 8 flash
// 2nd loop - pins 2 & 7 flash
// 3rd loop - pins 3 & 6 flash
// 4th loop - pins 4 & 5 flash

void s2m()
{
// Loop led_pin / 2 times
for (int i = 0; i < led_pin / 2; i++)
{
// Set pins high in pairs.
digitalWrite(led[i], HIGH);
digitalWrite(led[led_pin - 1 - i], HIGH);

// Pause for 200 ms
delay(200);

// Set the pins low again.
digitalWrite(led[i], LOW);
digitalWrite(led[led_pin - 1 - i], LOW);
}
}
``````
1 Like

Thank you so much for taking the time to help and have one more question, that is:
" led[led_pin - 1 - i]"
how was it calculated?

`led_pin` is the total number of pins (so 8 in your example).
`led_pin - 1` is 1 less than the total (so 7). This is because arrays number from 0, so your array elements are 0-7.
`led_pin - 1 - i` subtracts the loop counter from 7... so on the first loop this will be 7, 2nd loop it will be 6, etc.

1 Like

Oops

Where did you find this code?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.