On our current project we came up with a model train build monitor. The objective was to have the train move, while the build is green and to stop, when it goes red. The whole thing looks some what like this:
As a USB interface we chose to go for the Velleman K8055, which is available for about forty pounds and provides eight digital and two analogue outputs as well as two analogue and five digital inputs. The analogue outputs are provided as pwm signal.
The outputs are all open-collectors. Being a good developer I did of course anticipate a few more use-cases and hence designed the controller, so we could actually control the speed as well as the direction in which the train in moving. Essentially it uses a transistor to switch the train (using the pwm) and a relay to reverse the direction (yes this is somewhat lame). Also there is two free-wheeling diodes to protect the electronics from the high inductivity of the relay and the trains motor. This is the circuit diagram of the controller that goes between the K8055 and the train:
The K0855-board ships with a DLL to control the IO. Apparently there is a linux driver, which is much better than the windows version, but we are in a bit of a windows shop, so we went with the DLL. It turned out wrapping a DLL in a ruby script is fairly trivial:
require 'Win32API' open = Win32API.new("K8055D", "OpenDevice", ['L'] , 'L') outputAnalog = Win32API.new("K8055D", "OutputAnalogChannel", ['L','L'],'V') outputDigital = Win32API.new("K8055D", "WriteAllDigital", ['L'],'V') inputDigital = Win32API.new("K8055D", "ReadAllDigital", ,'L') open.Call(0) outputAnalog.Call(1, 10) # setting DA channel 1 to 10 outputDigital.Call(128) # reversing
Future plans include figuring out where the train currently is to stop in the station. The original plan was to use a reed switch, but that proved to be a bit unreliable, so the current thinking involves using a camera and something like hornetseye to get the exact position of the train.