Not sure where else to put this, but maybe someone playing with neopixels will find it handy.
Wanted to change colours randomly without the 'next' colour being close to the previous.
A bit limited in some way, but someone might have fun.
rndhue.py
Code: Select all
# Random colour methods for NeoPixel, does use more bytes to store random states
# Based heavly on http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
# Ported to Python by Electra
import neopixel
class NeoPixel(neopixel.NeoPixel):
def __init__(self,pin, n):
neopixel.NeoPixel.__init__(self,pin, n) # Pass on the __init__
from uos import urandom
self.hrnd = [0] * self.n
tmprnd=urandom(self.n)
for i in range(0,self.n):
self.hrnd[i] = tmprnd[i]*0.0039
# HSV values in [0..1] returns (r, g, b) values from 0 to 255
def hsv_to_rgb(self,h, s, v):
h_i = int((h*6))
f = h*6 - h_i
p = v * (1 - s)
q = v * (1 - f*s)
t = v * (1 - (1 - f) * s)
if h_i==0: r, g, b = v, t, p
if h_i==1: r, g, b = q, v, p
if h_i==2: r, g, b = p, v, t
if h_i==3: r, g, b = p, q, v
if h_i==4: r, g, b = t, p, v
if h_i==5: r, g, b = v, p, q
return (int(r*256), int(g*256), int(b*256))
# Move through semi random hue sequence, random saturation
# Optional parameter selected pixel otherwise all are affected
def rndhue(self,pix=-1):
from uos import urandom
for i in range(0,self.n):
if pix != -1:
i = pix
# Uncomment next line and indent two after for random skips
# for t in range(int(urandom(1)[0]/50)+1):
self.hrnd[i] += 0.618033988749895 # Golden ratio
self.hrnd[i] %= 1
self[i]=self.hsv_to_rgb(self.hrnd[i],(urandom(1)[0]/510)+0.5, 0.50)
if pix != -1:
return
import rgbled
import machine
import time
np = rgbled.NeoPixel(machine.Pin(4), 2)
while True: np.rndhue() ; np.write() ; time.sleep(1)