Talking to an Arduino from Ruby/Rails

As I’m in the process of building a full home-automation suite so I can finally open my garage door with my iPhone (stay tuned, more on that soon), I wanted to quickly post this since it actually wasn’t really easily found online and I spent a few minutes (ok, more like an hour) fiddling with this before I got it to work.

The code below takes data (you should pass in numeric 8-bit values, i.e. between 0×0 and 0xFF) and then read them out on the Arduino as usual. As a general note, working in dynamically typed language like Ruby is a major pain in the a** when you’re trying to fiddle with every bit and work with an 8-bit microcontroller on the other side of the wire. On a positive note,  Ruby has bit manipulation capabilities and it’s just so easy to build webapps with it…

The gist of the code below: Put the data into an array, pack it as unsigned characters, and then pump it into the serial port. The code below requires the ruby-serial gem.

class SerialGateway

  def initialize()
    puts "Starting serial gateway"
    begin
      # 9600, 8N1 on USB0
      @sp = SerialPort.new "/dev/ttyUSB0", 9600, 8, 1, SerialPort::NONE
      # release port on shutdown
      at_exit { do_at_exit() }
    rescue => e
      # sophisticated error handling
      puts "Cannot initialize usb device"
    end
    # only one serial access per time
    @send_mutex = Mutex.new
  end

  #
  # Send a command to the master device.
  #
  def sendCommand(command, targetAddress, data=[])

    if(data.length >4)
      raise "Sorry, maximum command data length is 4."
    end    

    # first one ASCII R (remote, 0x52)
    cmd = [ 0x52, command, targetAddress, data.size()]
    # add data array
    data.each { |d| cmd << d}
    # pack it into unsigned chars
    cmd = cmd.pack("C*")

    @send_mutex.synchronize do
     cmd.each_byte { |c| @sp.putc c }
    end

  end

end


Oh, and flipping back and forth between Ruby and C is a little weird :-)

Comments

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

-->