# Here's a formula for randomizing the colors of your light

It’s not impressive code, but I don’t know how to code and I couldn’t find it online so it took me some time to get right, so here’s the code if you’re gonna use a function. Improvements and criticisms welcome.

``````newmsg = Object();

r = Math.ceil(Math.random() * 255)
g = Math.ceil(Math.random() * 255)
b = Math.ceil(Math.random() * 255)

'transition': 30,
'entity_id': 'light.your_light's_entity_id',
'rgb_color': [r,g,b] } };
return newmsg;
``````

I’ve been using the same sort of logic. The only difference with mine was to also randomly change one of r, g, b to zero. I found with all of the LEDs having a value, the resultant colour often looked white-ish. The last two lines below randomly choose one to set to zero, which results in more intense colours.

``````var colours = [0, 0, 0];
colours[0] = getRandomTo(256);
colours[1] = getRandomTo(256);
colours[2] = getRandomTo(256);
var skip = getRandomTo(3);
colours[skip] = 0;
``````

Thanks very interesting. Thanks for sharing. I do plan on implementing something slightly more involved like that so I can have it randomly pull a color within certain ranges (i.e. turn all the lights a shade of blue in the between 6am -9am)

Also, I hadn’t been familiar with the getRandomTo function.

It’s not a built-in function - just one I had further down in the code:

``````function getRandomTo(x) {
return Math.floor(Math.random() * x);
}
``````
1 Like