class GPIO

Main class, to manage GPIO pins

Public Class Methods

new(pin, mode = OUT) click to toggle source

Initialize the GPIO pin

@param pin [Integer] GPIO pin number to use @param mode [String] pin mode : IN or OUT

# File lib/raspi-gpio.rb, line 41
def initialize(pin, mode = OUT)
  @pin = pin
  begin
    File.open("#{LIB_PATH}/unexport", 'w') do |file|
      file.write(@pin)
    end
  rescue Errno::EINVAL
    # Do nothing - the pin is already unexported
  end
  File.open("#{LIB_PATH}/export", 'w') do |file|
    file.write(@pin)
  end
  @mode = mode
end

Public Instance Methods

get_value() click to toggle source

Read the value of the pin

@return [Integer] pin's value : 0 or 1

# File lib/raspi-gpio.rb, line 71
def get_value
  File.open("#{LIB_PATH}/gpio#{@pin}/value", 'r').read
end
set_mode(mode) click to toggle source

Set the pin mode

@param mode [String] pin mode : IN or OUT @raise [UnknownMode] if the mode isn't IN or OUT

# File lib/raspi-gpio.rb, line 60
def set_mode(mode)
  raise UnknownMode, "gpio error : unknown mode #{mode}" unless mode == IN or mode == OUT
  File.open("#{LIB_PATH}/gpio#{@pin}/direction", 'w') do |file|
    file.write(mode)
  end
  @mode = mode
end
set_value(v) click to toggle source

Set a value to the pin

This method can only be used when the pin is in OUT mode

@param v [Integer] the value : LOW or HIGH @raise [NotOutMode] if the pin isn't in OUT mode @raise [BadValue] if the provided value isn't LOW or HIGH

# File lib/raspi-gpio.rb, line 81
def set_value(v)
  raise NotOutMode, "error : mode isn't OUT" unless @mode == OUT
  raise BadValue, "error : bad pin value" unless v.between? 0,1
  File.open("#{LIB_PATH}/gpio#{@pin}/value", 'w') do |file|
    file.write(v)
  end
end