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.

SerialPort

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 = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
 
loop do
  message = sp.gets
  message.strip
end

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).

Dino

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() {
  Serial.begin(115200);
  dino.setupWrite(writeCallback);
}

void loop() {
  while(Serial.available() > 0) dino.parse(Serial.read());
  dino.updateListeners();
  Serial.flush();
}

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 = Dino::Board.new(Dino::TxRx.new)
led = Dino::Components::Led.new(pin: 13, board: board)
 
[:on, :off].cycle do |switch|
  led.send(switch)
  sleep 0.5
end

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
end

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"
  
# Arduino.new(port, baudrate)
# Baudrate is optional, and defaults to 115200 when not specified
board = Arduino.new("/dev/ttyUSB1")

board.output(13)

loop do
  board.setHigh(13)
  sleep 0.5
  board.setLow(13)
  sleep 0.5
end
hardware.jpg
Tags ,