I have a sketch that mimics a candle flicker by randomly setting the brightness value of 4 LEDs. Technically the sketch I am using functions on my Ardino Micro, however, it uses 4 calls to analogWrite when, unless I’m mistaken, it could use only 2 lines to accomplish the same thing. My goal here is to make the code as efficient as possible. Here is what I have:
// Candle Effect Testing
int allLEDs[ ] = {6,9,10,11}; // Used to set pinmode for all LEDs to Output
//Need to also use this array in for loop to change brightness values
void setup()
{
pinMode(allLEDs, OUTPUT);
}
//I'm stuck as to how to reduce the following code by looping through allLEDs[]
void loop() {
for (int i = 0; i < allLEDs; i++) {
analogWrite(allLEDs[0], random(220)+135);// There must be a way to reduce these 4 lines to one
analogWrite(allLEDs[1], random(220)+135);// There must be a way to reduce these 4 lines to one
analogWrite(allLEDs[2], random(220)+135);// There must be a way to reduce these 4 lines to one
analogWrite(allLEDs[3], random(220)+135);// There must be a way to reduce these 4 lines to one
delay(random(100));
}
}
// Candle Effect Testing
int allLEDs[ ] = {6,9,10,11}; // Used to set pinmode for all LEDs to Output
//Need to also use this array in for loop to change brightness values
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
void setup()
{
for (int i = 0; i < ARRAY_SIZE(allLEDs); i++)
pinMode(allLEDs[i], OUTPUT);
}
//I'm stuck as to how to reduce the following code by looping through allLEDs[]
void loop()
{
for (int i = 0; i < ARRAY_SIZE(allLEDs); i++)
analogWrite(allLEDs[i], random(220)+135);
delay(random(100));
}
Thanks to marco_c (Nailed it right out of the gate!), larryd, UKHeliBob, and pert! Really appreciate the responses, code is running perfectly! Thanks to everybody that took the time to help! This is exactly what I was looking for:
// Candle Effect Testing
int allLEDs[ ] = {6,9,10,11};
#define array_size(a) (sizeof(a)/sizeof(a[0]))
void setup()
{
for (int i = 0; i < array_size(allLEDs); i++)
pinMode(allLEDs[i], OUTPUT);
}
void loop()
{
for (int i = 0; i < array_size(allLEDs); i++)
analogWrite(allLEDs[i], random(220)+135);
delay(random(100));
}
Oops, I didn’t notice marco_c’s post that was made while I was writing mine. I only noticed the UKHeliBob’s and didn’t look past that. Even so, it’s worth emphasizing this very useful technique for determining the number of elements in the array. It’s great because your code will automatically adapt if you change the number of LEDs.