Generating random colours (unicornhat)

I am trying to generate random colours on my unicornhat using the following code

from random import randint
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
unicornhat.set_pixel(6, 0, r, g, b)

the trouble with this is every now and then I get a bad colour that doesn’t display on the unicornhat, I assume it is generating “0, 0, 0”

is there a better way, maybe only generate safe / approved colours

pixels below a certain brightness won’t display. I would add a conditional that sums up the rgb tuple randomly generated and discard those below a certain threshold.

actually, I’m talking from my back side - you need to check for each colour separately and regenerate any random value below the minimum threshold required for the pixel to light up.

Instead of generating random R, G, B values, perhaps you could use a different colour space- HSV for example- and generate random hues? Keeping the saturation and value constant.

You can use the hsv_to_rgb method in colorsys to convert 3 floating point values- between 0.0 and 1.0- representing Hue, Saturation and Value into RGB:

import colorsys
hue = randint(0, 359) # (In degrees)
sat = 1.0
val = 1.0
r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(hue/359.0, sat, val)]

The int(c * 255) converts the 0.0-1.0 float values returned by hsv_to_rgb into the 0-255 range understood by Unicorn HAT.

If you want variable saturation and brightness you could also randomise those between known good values.

HSV has other benefits, too, by adjusting your random range you can pick portions of the hue wheel that contain complementary colours to randomise. For example you might just want shades of pink and blue, ie: randint(190,320)

Googling ‘hue wheel’ will give you some guidance about what colours appear where, for example;

1 Like

Perfect! That is exactly what I wanted, worked right away!