The best kittens, technology, and video games blog in the world.

Saturday, February 13, 2016

Adventures with Raspberry Pi: RGB Led

I've done regular LEDs before, so I wanted to try RGB Led now.

RGB Led is like red, green, and blue RED in one package, sharing common ground (so 4 pins total), supposedly allowing any color.

Now your first idea might be to use analog output and set diode intensity to control red, blue, and green, and that would work with a regular lamp, more or less, but diodes are really just on or off, so we need to do pulse width modulation.

Unfortunately it turns out that Raspberry Pi, ruby and pi_piper gem are not fast enough for that. This code really ought to work:

class RGBLed
  def initialize
    @blue  = => 17, :direction => :out)
    @red   = => 22, :direction => :out)
    @green = => 27, :direction => :out)

  def display(r,g,b)
    while true
      @red.send(if rand < r then :on else :off end)
      @green.send(if rand < g then :on else :off end)
      @blue.send(if rand < b then :on else :off end)

  def on

  def off

led =

With iterations being done at a bit oven 1300 iterations per second, it should provide half intensity white light. Instead it's flashing all the colors randomly, so presumably something downstream from ruby is being really slow.

There's also minor problem of green LED component being much brighter than others (all use 220 hm resistors, and changing I/O ports or resistors around doesn't change that).

All that is a shame, as software PWM is a pretty useful building block for a lot of things, and if that doesn't work, I won't be able to do a ton of other thing. If anybody has any ideas, please tell me.

No comments: