简体   繁体   中英

Python - RGB LED Color Fading

I have looked around extensively trying to find a method to fade between one color to another in Python. Most of the examples I've found are usually specific to a device or in another language which doesn't translate well.

I currently have a modified piece of code which was used to create a breathing effect which worked pretty well fading from 0 to 255 for example. What I have now sets the from color, say green; flickers; then sets the to color:

def colorFade(strip, colorFrom, colorTo, wait_ms=20, steps=10):
    steps = 200

    step_R = int(colorTo[0]) / steps
    step_G = int(colorTo[1]) / steps
    step_B = int(colorTo[2]) / steps
    r = int(colorFrom[0])
    g = int(colorFrom[1])
    b = int(colorFrom[2])

    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

Calling code:

colorFade(strip, [200, 0, 0], [0, 200, 0])

It sounds like you want to start at colorFrom , and gradually step along a straight line until you reach colorTo .

What this code does is start at colorFrom , then increment the current color as if you were stepping from black to colorTo .

Hard to be sure without the full code, but it looks like you should replace this:

step_R = int(colorTo[0]) / steps
step_G = int(colorTo[1]) / steps
step_B = int(colorTo[2]) / steps

with this:

step_R = (colorTo[0] - colorFrom[0]) / steps
step_G = (colorTo[1] - colorFrom[1]) / steps
step_B = (colorTo[2] - colorFrom[2]) / steps

Edit: And, as jasonharper pointed out, you may be doing integer division. Not clear what your types are. If you're using Python 2, / is integer division. In Python 3, it's floating point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM