Coding several individual variables in 'chunks'

Hello,

I'm still fairly new to the programming language used for Arduino's. I was wondering if there is anyway to tell several variables to do the same thing? For example having 7 individual LEDs and commanding them to turn on/off in a single line of code instead writing a line of code for each LED?

So having...
analogWrite(led1....led7, 255);
delay(50);
analogWrite(led1....led7, 0);
delay(50);

instead of having....

analogWrite(led1 , 255);
analogWrite(led2 , 255);
analogWrite(led3 , 255);
analogWrite(led4 , 255);

and so forth.

Any guidance would be greatly appreciated.

analogWrite(led1 , 255);analogWrite(led2 , 255);analogWrite(led3 , 255);analogWrite(led4 , 255);

^ single line of code

The only other way to do what you desire is to create a loop that runs through all of your variables. Then you can make it a function and then call the function in a single line of code.

If you find yourself putting numbers on the ends of your variable names, then what you really need is an array. If you had those pin numbers in an array then you could use a for loop.

But no, there's no way to make the analogWrite function take more than one pin number.

Find a C++ tutorial on the interwebs, and read the sections on arrays and on structs.

If you find yourself with a number of identical variables and you have to do the same thing to all of them (led1, led2, led3), then you need an array.

[nobbc]byte led[3];[/nobbc]

If you find yourself with a number of identical sets of variables (garagePin, garageDebounce, garageState, doorPin, doorDebounce, doorState, catflapPin, catflabDebounce, catflapState), then you need structs and meybe even classes.

[nobbc]struct Cluster {
  byte pin;
  long debounce;
  boolean state;
} garage, door, catflap;[/nobbc]

And if you find you have both (activator1Pin, activator1Debounce, activator1State, activator2Pin, activator2Debounce, activator2State, activator3Pin, activator3Debounce, activator3State), then you probably want an array of structs.

[nobbc]Cluster activator[3];[/nobbc]

Google "C++ tutorial" - there are jillions on the web - and read about arrays and structs.

#define led1 20
#define led2 21
#define led3 22
#define led4 23
#define led5 24
const int ON = HIGH;
const int OFF = LOW;

int led[5] = {led1, led2, led3, led4, led5};


void turnLEDs (int state) {
  for (int i=0; i < 5; i++) {
    digitalWrite(led[i], state);
  }
}


void loop() {
  turnLEDs(ON);
  delay(500);
  turnLEDs(OFF);
  delay(500);
}

There is a little bit of code in the beginning, but once it’s all setup, it becomes simple to just turn them all on or off.

Of course this assumes that the LEDs are attached to digital ports on the Arduino, and also sunk to ground with an appropriate pull up resistor (never connect an LED from voltage to ground without a series resistor), OR you have the pull up resistor enabled on the digital port.

Hope that helps.