Go Down

Topic: Random number for RGB Led (Read 821 times) previous topic - next topic

dehlen

Hey,
i have 9 RGB Led's. Each of this led should light up red, green or blue. Which color the led lights up should be randomly.
Therefore i wrote this method (which works) but i hope that you can give me a better solution:
Code: [Select]

int rand=random(0,2);
if(rand == 0) {
lightRed(led1);
}
else if (rand == 1) {
lightGreen(led1);
}
else if (rand == 2) {
lightBlue(led1);
}

int rand2=random(0,2);
if(rand2 == 0) {
lightRed(led2);
}
else if (rand2 == 1) {
lightGreen(led2);
}
else if (rand2 == 2) {
lightBlue(led2);
}
.....

int rand9 = random(0,2);
if(rand9 == 0) {
lightRed(led9);
}
else if (rand9 == 1) {
lightGreen(led9);
}
else if (rand9 == 2) {
lightBlue(led9);
}



....way to much code. There must be a more elegant solution.
Thanks for your help.

PaulS

Code: [Select]
int rand=random(0,2);
This will result in rand containing either 0 or 1. The upper limit is the smallest number not returned. Why? A dumb decision by the Arduino team.

Quote
i hope that you can give me a better solution

When you find your self doing the same thing over and over, it's time to write a function. That and arrays would eliminate more than 90% of your code.

dehlen

Yeah sure so my function would be something like
Code: [Select]
void randomColor(int led) {
int rand = random(0,3);
if (rand == 0) {
colorRed(led);
}
else if (rand == 1) {
colorGreen(led);
}
else if (rand == 2) {
colorBlue(led);
}
}

and then
for (int i = 0;i<ledArray.length;i++) {
randomColor(i);
}


right ?

I will try that out now.

billroy

If you had an access routine that worked like this:
Code: [Select]

void lightLED(int led, int color) { …implementation here… }

You could implement that long section of code as:
Code: [Select]

lightLED(1, random(0,2));
lightLED(2, random(0,2));



-br

PaulS

Quote
You could implement that long section of code as:

Or, even better as:

lightLED(1, random(0,3));
lightLED(2, random(0,3));

Or, even better in a for loop...

dhenry

The original arrangement of lighting up just one color per led is weird, particularly in light of the multiple leds.

Here is what I would do:

Code: [Select]

#define LED_RAND(led) do {if (random(0, 2)) lightBlue(led); if (random(0, 2)) lightRed(led); if (random(0, 2)) lightGreen(led);} while (0);

//in your application code:

  LED_RAND(led1); //randomly lite up a led
  LED_RAND(led2); //randomly lite up a led
...
  LED_RAND(led9); //randomly lite up a led


It will produce random patterns on each led, up to 8 combinations (including dark/off).

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy