I'm currently studying Arduino and I need help about Arrays.
From what I know we can use arrays to declare the pins rather than giving it names and pin # separately, but is it possible to declare the whole array as output instead of typing the array elements 1 by 1?
I want to use array to efficiently write my code rather than a long one.
int LED[] = {2,3,4,5,6,7,8,9};
void setup() {
pinMode(LED,OUTPUT);
}
Can I also use the whole array to blink up all the pins at the same time without specifying the array elements?
Well, you're right of course, it does what he asked for, but it's pretty intimidating.
@OP: Here's a simpler version to understand what's going on. The previous version just moves the for loop into a separate function to reduce the number of unnecessary repetitions.
Some notes:
Line 1: the array is declared const because its contents don't change. This is good practice to prevent yourself from accidentally changing it, by using if (LED[0] = 2) instead of if (LED[0] == 2), for example. The data type is uint8_t because a pin number cannot be negative (u = unsigned) or greater than 255 (an unsigned integer of 8 bits can save 2⁸ = 256 numbers, i.e. [0, 255]).
Line 2: the number of elements of an array is the total number of bytes of the array divided by the number of bytes of one element.
Line 5: just as for the pin numbers, the uint8_t type is used for the loop index, because it's positive and less than 256.
If you want to understand how the previous example works (maybe in a couple of weeks/months), the keywords to look for are function templates and range-based for loops