blinkin blue leds with ruby

October 23, 2016
#!/usr/bin/env ruby

require 'rpi_gpio'

def init
    RPi::GPIO.set_numbering :bcm

    [17,18,27,22].each do |pin|
        RPi::GPIO.setup pin, :as => :output
        RPi::GPIO.set_low pin
    end
end

def cycle
    [17,18,27,22,27,18].each do |pin|
        RPi::GPIO.set_high pin
        sleep (0.25)
        RPi::GPIO.set_low pin
    end
end

init
(1..9).each{ cycle }

RPi::GPIO.reset

This is the Ruby version of my Cylon LED test cycler that I’ve written in various languages on Arch Linux and the Raspberry Pi. This time it was Ruby’s turn to see if I could use it to manipulate the various I/O subsystems on the Pi. Since setting output pins to drive LEDs is the easiest place for me to start, I wrote the code you see above. Before I could make it work I had to install the rpi_gpio gem. To get some idea of how to use it I looked at the GitHub repository for rpi_gpio. The reason for this is to be able to bridge between the Ruby on Rails work I started earlier this week with both input and output I/O. The only other comment I will make is to make sure that the udev rules have been set up to manipulate the I/O as a regular user. Trying to run the code shown above as root will fail, as the installation of rpi_gpio was local to a regular account, not globally installed.

My only comment on rpi_gpio so far is this: I discovered I had to code a set_low immediately after every enabling of a pin as an output, as the pin was enabled high. I consider this a bug, and as it stands it may not be suitable for what I need. If even a microsecond pulse goes out from those pins after being enabled by Ruby then that’s enough to cause a false start on that pin. The Ruby code isn’t something to write home about, just something to do some very basic testing.