Arduino x Ruby

If on a Friday night you've ever found yourself sprawled out on the floor surrounded by jumper wires, resistors, prosecco and a judgmental cat, this post is for you.Arduino gives me a warm creepy little feeling inside and Ruby is terribly pretty, so I've been excited to discover there are a variety of ways for them to co-exist.


This gem allows you to easily communicate with the Arduino over your serial port.

require 'serialport'
port_str  = '/dev/tty.usbmodem1411'  # This may be different for you
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity    = SerialPort::NONE
sp =, baud_rate, data_bits, stop_bits, parity)
loop do
  message = sp.gets

The loop reads and returns every message that comes through the serial port from the Arduino to your computer. To send information the other way, use sp.write(message).


Dependent on SerialPort, this gem allows for more abstract interaction with your components by using a library that responds to requests over the serial connection.

Run dino generate-sketch serial from the command line to create a sketch that can be uploaded to the Arduino.

#include "Dino.h"
#include <Servo.h>
Dino dino;

// Dino.h doesn't handle TXRX. Setup a function to tell it to write to Serial.
void writeResponse(char *response) { Serial.print(response); Serial.print("\n"); }
void (*writeCallback)(char *str) = writeResponse;

void setup() {

void loop() {
  while(Serial.available() > 0) dino.parse(;

Now you can actually control the Arduino from a Ruby file just by running that file from the terminal. The example code below creates a simple LED blinker.

require 'dino'

board =
led = 13, board: board)
[:on, :off].cycle do |switch|
  sleep 0.5

Arduino Firmata

With this gem you can embed analog and digital read and write functionality in your program using Ruby. Here's the same LED blinker.

require "arduino_firmata"

arduino = ArduinoFirmata.connect
puts "firmata version #{arduino.version}"

loop do
  arduino.digital_write 13, true
  sleep 0.5
  arduino.digital_write 13, false
  sleep 0.5

Arduino Gem

Okay, this one is really cool. The Arduino gem is an API that allows you to prototype your programs without constantly burning them to the board. Just install the gem and load the arduino.pde file to the board once. The gem lets you talk to the Arduino, to do things like setting and getting pin states. You can prototype right in irb!

require "arduino"
#, baudrate)
# Baudrate is optional, and defaults to 115200 when not specified
board ="/dev/ttyUSB1")


loop do
  sleep 0.5
  sleep 0.5
Tags ,