tags:

views:

349

answers:

2

I have a tiny shell script that writes to a serial device:

#!/usr/bin/ruby

require 'rubygems'
require 'serialport'

@sp = SerialPort.new "/dev/tty.usbserial-A6004cNN", 19200
@sp.write ["\x01\x01\x04\x00", "n", "\xff\xff\xff"]

This doesn't write to the serial device when I run ./script.sh in that directory. However when I jump into IRB and run:

require 'serialport' #=> true
@sp = SerialPort.new "/dev/tty.usbserial-A6004cNN", 19200 #=> #<SerialPort:0x1016bd698>
@sp.write ["\x01\x01\x04\x00", "n", "\xff\xff\xff"] #=> 8

This way works... I'm baffled. Could it be the way i'm outputting my byte array? That doesn't seem right, its just raw ruby here, doesn't have an dependancies that are obvious. Also the script doesn't throw an exception, it executes just fine, however the device just doesn't respond.

How would I go about debugging this? I'm not sure where to start.

+4  A: 

I don't know the SerialPort gem, but it's possible that output to the serial port is being buffered, and not flushed before the script exits, while IRB gives it time to flush the buffer as you go back to a prompt. I'd try adding @sp.flush and see if that helps at all.

Brian Campbell
What!? I can't believe it was that simple, great, thanks a lot Brian. +1
Joseph Silvashy
A: 

Instead of having it be a shell script, make it a .rb ruby script, then call it with

ruby <name_of_my_script>.rb

Then everything should work fine.

Scott S.
The #! line at the beginning of the script lists the interpreter. It doesn't matter what it's named (I would assume that the .sh listed in the question was a typo).
Brian Campbell