Ruby serialport gem.

Posted on August 31st, 2008 in Electronics, Nerdy, ruby by toholio

Ruby-serialport doesn’t play well with RubyGems. Trying to require 'serialport' when using RubyGems results in:

NameError: (eval):1:in `private_class_method': undefined method `create' for class `Class'
        from (eval):1
        from (eval):1
        from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
        from (irb):2

The quick fix to get around this is by doing:

Kernel::require 'serialport'

It would be nicer if we could avoid the conflict with RubyGems. It would be even nicer if the serialport library was itself packaged as a gem. Turns out this has been done by aaronp but it doesn’t take advantage of GitHub’s automatic gem builder and doesn’t build correctly using GCC.

I’ve cloned and tidied the git repository. This gem version should build the needed native extension and work on both POSIX compatible and Windows operating systems.

Installing the serialport gem

If you haven’t configured GitHub as a gem source yet you will need to run the following command:

gem sources -a http://gems.github.com

Then, you can install the gem as normal:

sudo gem install toholio-serialport

Unlike the official ruby-serialport extension, this gem works with RubyGems (duh!). When you want to use it you should only need to do the following:

require 'rubygems'
require 'serialport'

On a side note: git and GitHub rock. Forking, contributing to and merging projects should be this simple.

Ruby on Nickel-Silver Rails

Posted on March 19th, 2008 in Electronics, Nerdy, ruby by toholio

It’s been hot here in Melbourne so rather than actually leaving the house to do anything I’ve been sitting in front of a fan mucking about with my computer. Yesterday afternoon I created a Ruby implementation of a LocoNetOverTCP server. I’ve decided to call it Nickel-Silver because that’s the common name of the alloy most model railroad track is made of and some trifling project has already used the name “Ruby on Rails”. Here’s a quick list of Nickel-Silver’s features:

  • Implements all of LocoNetOverTCP protocol version 1
  • Multithreaded (inherits from GServer)
  • Easily extendable interface for LocoNet hardware devices
  • Only about 100 lines of code (according to egrep -c -v "^[ ]*$|^[ ]*#")
  • Base implementation uses only the standard library
  • Included “driver” for the LocoBuffer-USB hardware uses a single extra package, ruby-serialport
  • It’s written in Ruby

Hardware setup

Currently the only “driver” provided connects to a LocoNet network via a LocoBuffer-USB. So a complete hardware setup looks something like the following diagram.

Electrical setup for LocoNetOverTCP server

LocoNetOverTCP clients connect to the server running on the computer which acts as a proxy to the LocoNet. This removes the need for each computer to have its own LocoNet hardware interface. It also removes the need for the clients to be physically located near layout.

Server setup

Assuming we’re going to use the included LocoBuffer-USB “driver” we need to do the following to start a server.

  1. Install ruby-serialport if you haven’t already.
  2. Install the nickel-silver-server gem
  3. Open a new ruby script in your favourite editor or start IRB.
  4. Determine the serial port your LocoBuffer-USB is connected to.
  5. Create an instance of the LocoBufferUSB “driver” class.
  6. Create an instance of the server with the “driver” as a parameter.
  7. Run the script

To install the server’s gem open a terminal and run:

gem install nickel-silver-server

That should get everything that’s required with the exception of ruby-serialport which you must install manually.

My LocoBuffer-USB is connected to my computer via the virtual serial port /dev/cu.usbserial-FTQ1P4JC so a complete script for my server would look like the following.

#!/usr/bin/ruby
 
require 'rubygems'
require 'nickel-silver-server'
 
# connect to a LocoBufferUSB on the virtual serial port /dev/cu.usbserial-FTQ1P4JC'
interface = NickelSilver::Server::Interface::LocoBufferUSB.new( '/dev/cu.usbserial-FTQ1P4JC' )
 
# create a server using the default port (i.e. 5626, 'loco' spelt on a phone keypad)
# using our freshly connected LocoBuffer-USB
server = NickelSilver::Server::LocoNetServer.new( interface )
 
# start the server
server.start
 
# wait for the server to stop before exiting
server.join

Documentation

Currently this post is the only documentation not contained within the gem. You can view the gem’s rdoc documentation at http://nickel-silver.rubyforge.org/nickel-silver-server/rdoc/

Sending trains down the track

Until boredom strikes again there isn’t a Ruby throttle program that can interface with Nickel-Silver. Instead we can use the excellent Java program JMRI to talk to our trains.

JMRI already knows about LocoNetOverTCP servers right out of the box. Starting JMRI and looking at the preferences we can wrangle things to look like the following.

JMRI connecting to Nickel Silver

Now we’re ready to go. Selecting Tools > Throttles > New Throttle gives us a throttle window where we can enter a locomotive address and make it move.

Implementing a new “driver”

The only LocoNet computer interface I have access to is a LocoBuffer-USB. I’d highly recommend one to anyone who is interested but acknowledge that there are many people with other hardware.

As long as you can send and receive LocoNet packets via your hardware in Ruby (or in any language that may be used for Ruby extensions) you can write a “driver”.

The only things a “driver” needs to be able to do are:

  • Store incoming packets as FixNums representing bytes in a buffer array
  • Send outgoing bytes (represented as FixNums in a buffer array) to LocoNet
  • Use a Mutex to lock access to the buffers when in use (remember Nickel-Silver is multithreaded)
  • Provide a method that causes your interface to start collecting packets

The interface is simple. Only the following public methods are needed:

  • Accessors for input_buffer, output_buffer and io_mutex
  • run() which starts buffering

How you do this is up to you but you can take a look at LocoBufferUSB.rb to get an idea of how it might be done. A stub driver might look like the following…

class SomeLocoNetInterface
  attr_accessor :input_buffer, :output_buffer, :io_mutex
 
  def initialize
    # these may be modified at any time by the server
    @input_buffer = []
    @output_buffer = []
 
    # only make changes when locked using @io_mutex
    @io_mutex = Mutex.new
  end
 
  def run
    loop do
      # get incoming bytes
      if byte_waiting?
        @io_mutex.synchronize do
          # byte getting code here
          @input_buffer << get_byte
        end
      end
 
      # send outgoing bytes
      until @output_buffer.empty? do
        @io_mutex.synchronize do
          # send a byte
          send_byte( @output_buffer.shift )
        end
      end
    end
  end
 
end

Remember that either buffer may be empty or already containing data and that you must lock the mutex for the minimum amount of time possible.

Isn’t there already a LocoNetOverTCP server project?

Yes there is! It’s called LbServer and is hosted over at SourceForge.

If you’re looking for a mature LocoNetOverTCP server that’s probably the place you should start. Unlike my implementation there are more people than just me using it and they probably have more bugs fixed than I’m likely to notice any time soon.

MacOS X PIC toolbox

Posted on September 13th, 2006 in Electronics, Nerdy by toholio

I recently needed to install all the PIC programming tools I use on several Macs. Since people often ask for help installing these kinds of things I’ve decided to put together an installer package containg all the tools I use for the majority of my PIC’n needs. Hopefully someone else will find it useful.

The installer contains universal binaries for:

  • Jeff Post’s PK2 v2.01 – for operating the PICkit2 programmer hardware
  • GPUTILS v0.13.4 – assembler, linker, etc
  • sdcc v2.6.0 – C compiler

I have only tested the installer and resulting binaries on Macs running 10.4.7 (x86 and PPC) so if you try it under a different version of OS X, please let me know how it works.

The following installer contains all three packages (you can choose which ones to install).

Metapackage icon.
PIC toolbox (8.1MB)

IMPORTANT:The installer wont reconfigure your PATH, MANPATH or SDCC_HOME environment variables automatically. The things to add are:

  • /usr/local/bin to PATH
  • /usr/local/man to MANPATH
  • SDCC_HOME=/usr/local

For most people these can be configured by opening a terminal and running the following commands:

echo 'export PATH=/usr/local/bin:$PATH' >> ~/.bash_profile
echo 'export MANPATH=/usr/local/man:$MANPATH' >> ~/.bash_profile
echo 'export SDCC_HOME=/usr/local' >> ~/.bash_profile

PIC micro-controller programming on MacOS X.

Posted on July 4th, 2006 in Electronics, Nerdy by toholio

For a long time I’ve been frustrated by the lack of tools for programming micro-controllers (PICs specifically) using MacOS X. Most bit banging serial programmers wont work with a USB-to-Serial adapter, though I’m told some commercial ones do. There are some USB programmers available but until recently I wasn’t able to find one that was compatible with the 16F88 (PDF, datasheet) and had MacOS drivers available.

Enter the PICkit 2

After finally getting tired of SSHing into a Linux box in another room every-time I wanted to write to a PIC I started looking for a USB based programmer with support for the 16F88. I was pleasantly surprised to see that the firmware for Microchip’s PICkit2 had been updated to work with the 16F88 (as of version 1.20). The PICkit is a nicely made unit (about 10cm x 4cm x 1cm) that can be bought, with a low pin count demo board included, directly from Microchip for under AU$100.


PICkit 2

This still left me with the problem of Mac drivers but it didn’t take long to find Jeff Post’s PK2, an open source program for working with the PICkit2.

Using PK2 with MacOS X

Version 2.00 of PK2 works well well with MacOS. Older versions may work too but I haven’t done much testing with them. The program is easy to build and there is a native HID report which means that there is no need for MacOS users to muck about with libusb. Very nice indeed. When building make sure you use the osxhid Makefile target (unless you really want to use libusb). Once built and installed PK2 can be used to update the programmer’s firmware. Everything should be good to go and the programmer should be able to see the PIC it is connected to like so:

tobie@Tea-Chest ~ $ pk2 -device

PK2 version 2.00 - 2006/07/02
 pk2 -device
Communication established. PICkit2 firmware version is 1.21.0

Device ID 0x0760
PIC16F88 Rev 5 found
  Family:         Midrange
  Program size:   0x1000 (4096) words, width 0x3fff
  Eeprom size:    0x100 (256) bytes
  ID location:    0x0
  ID size:        0x4 (4) bytes
  Device ID       0x0760
  Write burst     4
  Program command O
  Program mode    n
  Program timing  n
  Data timing     d
  Erase mode      0
  CP mask         0x0834
  Bandgap mask    0x0000 0x0000
  Config mask     0x3fff 0x0003
  Save osccal     0
  Save bandgap    0
  Command table   63 00 02 03 04 05 06 08 18 17 1f 1f ff ff ff ff

Handy resources

The PICkit 2 comes with a CD-ROM which contains lots of examples and code for the supplied PIC16F690 including several lessons which should help someone not familiar with PIC programming to get a good grasp on the basics. For other PICs there are many forums and mailing lists on the internet including Microchip’s own. A quick Google search should point you in the right direction.

For updates and discussion of PK2 there is the pickit-devel Google group.