Go Down

### Topic: Random number for RGB Led (Read 1 time)previous topic - next topic

#### dehlen

##### Dec 11, 2012, 03:50 pm
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.

#### PaulS

#1
##### Dec 11, 2012, 03:57 pm
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

#2
##### Dec 11, 2012, 04:00 pm
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 thenfor (int i = 0;i<ledArray.length;i++) {randomColor(i);}`

right ?

I will try that out now.

#### billroy

#3
##### Dec 11, 2012, 04:01 pm
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

#4
##### Dec 11, 2012, 04:07 pm
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

#5
##### Dec 11, 2012, 04:51 pm
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