1

I'm using int with 14 LEDs to specify pins, but I don't want to use int 14 times, like this:

int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 7;
int led7 = 8;
int led8 = 9;
int led9 = 10;
int led10 = 11;
int led11 = 12;
int led12 = 13;
int led13 = 45;
int led14 = 46;

is there any way to not do this? Also, to define them as output, is there any way to avoid using pinMode(***, OUTPUT) 14 times as well?

0

1 Answer 1

4

The word you are looking for is array.

An array is like a list of values all of the same type. For instance, your LED pins could be specified as:

int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

You can then access the LEDs by number. Note that arrays start counting from zero not from one, so you would have:

leds[0]
leds[1]
leds[2]
... etc to ...
leds[12]
leds[13]

It's great for using them in an array:

for (int i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

If the values are never going to change, as in this case since they are pin numbers, the array should be declared const so it doesn't take up any of your precious RAM:

const int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

Also you should get into the habit of tailoring the data types to the expected values. If the values are never going to exceed 255 then you should use "byte" not "int", or better still the C standard "uint8_t".

const uint8_t leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

for (uint8_t i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

An int takes two bytes, so using int when you can get away with uint8_t means you're wasting half the memory.

Not the answer you're looking for? Browse other questions tagged or ask your own question.