Cgpio
A simple GPIO Wrapper in Ruby (which uses C memory mapping to access the GPIO)
require 'cgpio'
# switch on a led on port 48
led = Cgpio.new(48)
led.on
Tested with Linux-Kernel Version "4.1.6" on
WARN: the gem is not stable yet!
Features
- set/get value
- set/get direction
- virtual GPIO
- memory mapped GPIO access
Installation
This gem uses C extension, so you need build-essentials (gcc, make)
gem install cgpio
Usage
Example
require 'cgpio'
# setup a new port (output is default)
led = Cgpio.new(48)
# setup a new input port
switch = Cgpio.new(66, direction: :in)
# connect led with switch
loop do led.value = switch.value end
Initializing a port
# setup a new port (output is default)
led = Cgpio.new(48)
# setup a new output port with HIGH as initial state
led = Cgpio.new(66, value: true)
# setup a new input port
switch = Cgpio.new(66, direction: :in)
Note: The initialization will export the port (/sys/class/gpio/export) if it is not exported already. But when the GC (Garbage Collector) deletes this object, the port will not be unexported.
Set direction of port
# port as output
led.direction = :out
# port as input
switch.direction = :in
Get direction of port
# returns :in or :out
dir = switch.direction
Set value of port
# set value to true
led.value = true
# or
led.on
# set value to false
led.value = false
# or
led.off
Read value of port
val = switch.value
val = switch.on?
val = switch.off?
Get static info about port
# get port number
nr = port.nr
Virtual GPIO
When you want to run your program on a hardware which don't have GPIO, you can use virtual GPIOs.
For this you have to configure the Cgpio before you use it:
# put this at the beginning of your program
Cgpio.configure do |config|
# use virtual gpio instead of real gpio
config.virtual = true
end
Value changed event
You can can define a function which will be called when the value of the virtual GPIO changes:
# will be called when value changes
led.value_change do |new, old|
puts "led change value from #{old} to #{new}"
end
License
The gem is available as open source under the terms of the MIT License.