Timmo - 10 months ago 47
Python Question

# Python - Looping From Black to a Set Color

I am writing a breathing effect for the

`neopixel`
library and need to essentially increment three numbers to create a
`Color`
for a set period.

I can do this pretty easily with black to white:

``````def colorBreathing(strip, color, wait_ms = 5):
# Breathing lights
for b in range(200):
for i in range(strip.numPixels()):
strip.setPixelColor(i, Color(b, b, b))
strip.show()
time.sleep(wait_ms / 1000.0)
for b in reversed(range(200)):
for i in range(strip.numPixels()):
strip.setPixelColor(i, Color(b, b, b))
strip.show()
time.sleep(wait_ms / 1000.0)
``````

The question is, how would I do this with another color that the user sets? So a set color could be something like
`Color(200, 180, 230)`
for example.

If you have `steps = 200` and `(200, 180, 230)` then use

``````step_R = 200/steps
step_G = 180/steps
step_B = 230/steps
``````

and then `Color( int(step_R*b), int(step_G*b), int(step_B*b) )`

Not tested:

``````destination = (200, 180, 230)

steps = 200

step_R = destination[0]/steps
step_G = destination[1]/steps
step_B = destination[2]/steps

for x in range(steps):
r = int(step_R*x)
g = int(step_G*x)
b = int(step_B*x)
c = Color(r, g, b)
for i in range(strip.numPixels()):
strip.setPixelColor(i, c)
strip.show()
time.sleep(wait_ms / 1000.0)

for x in range(steps, -1, -1):
r = int(step_R*x)
g = int(step_G*x)
b = int(step_B*x)
c = Color(r, g, b)
for i in range(strip.numPixels()):
strip.setPixelColor(i, c)
strip.show()
time.sleep(wait_ms / 1000.0)
``````

You can use `r += step_R` instead of `r = int(step_R * x)`

Not tested:

``````destination = (200, 180, 230)

steps = 200

step_R = destination[0]/steps
step_G = destination[1]/steps
step_B = destination[2]/steps

r = 0
g = 0
b = 0

for x in range(steps):
c = Color(int(r), int(g), int(b))
for i in range(strip.numPixels()):
strip.setPixelColor(i, c)
strip.show()
time.sleep(wait_ms / 1000.0)
r += step_R
g += step_G
b += step_B

for x in range(steps):
r -= step_R
g -= step_G
b -= step_B
c = Color(int(r), int(g), int(b))
for i in range(strip.numPixels()):
strip.setPixelColor(i, c)
strip.show()
time.sleep(wait_ms / 1000.0)
``````