1. Computing

Interfacing with the Arduino on Linux

By

The Arduino is a popular open-source microcontroller board. This is a tiny computer that can be used to gather input from sensor, and drive electronic displays, LEDs, and just about anything else. However, in addition to all this, it can also communicate with your PC via a serial port (or virtual serial port over USB).

Ruby doesn't have the ability to use serial ports out of the box. Because of this, you'll need a gem. Also, since accessing the serial port is different on every operating system and requires low-level system calls, it's not as easy as a simple gem install for every system.

On Linux, you have the SerialPort gem. Installing this gem is not very difficult, but it does require you have a C compiler and the Ruby development packages installed. This is different for every Linux distribution, but on Debian and Ubuntu Linux, installing the packages build-essential and ruby1.8-dev should be sufficient. After that, it's a simple gem command to install SerialPort.

 $ gem install ruby-serialport 

This gem is available on Windows, and can apparently Visual C++ and Borland C++ to compile itself.

Once installed, it's simple to use. On Linux, your Arduino serial device will show up as something like /dev/ttyUSB0. Simply pass that to the SerialPort constructor and you're ready to read and write.

 #!/usr/bin/env ruby
 require 'rubygems'
 require 'serialport'
 
 # Remember to pass the baud rate as well
 port = SerialPort.new( '/dev/ttyUSB0', 9600 )
 
 # Read a string from the Arduino
 message = port.gets
 
 # Write just like any other IO device
 port.puts "Hello Arduino!"
 

It's as easy as that, you're now in communication with programs running on the Arduino using Ruby.

See More About
  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. Interfacing with the Arduino on Linux

©2014 About.com. All rights reserved.