JP Silvashy JP Silvashy - 3 months ago 14
Ruby Question

Writing Byte Arrays to serial with Ruby

I'm not clear on how to write simple byte code arrays with ruby, more-so I'm absolutely stumped on how to use the Ruby SerialPort library, well to be honest I have it working pretty well however I have only been successful in sending ASCII over the serial port.

For example it's really simple to write ASCII:

@sp = SerialPort.new "/dev/tty.usbserial-A6004cNN", 19200
@sp.write "test"


Which obviously writes
test
to that serial device. This works fine and I've been able to get all the expected results sent to a micro-controller (arduino) in this case. The issue is that I need to write output which the serial device will read like so:

{0x01,0x09,0x04,0x00, 'f',0xff,0xcc,0x33}


I've tried using
str.unpack
but am still unable to produce the desired hex values output as bytes as above.

In Java it is simple using it's serial library:

byte[] cmd = { 0x01,0x09,0x04,0x00, 'f',(byte)0xff,(byte)0xcc,(byte)0x33 };
serialPort.write( cmd );


How can I output the proper bytecode to my serial device with Ruby?

Answer
@sp.write [32.chr, 7.chr, 8.chr, 65.chr].to_s
@sp.write ["\x01\x09\x04\x00", 'f', "\xff\xcc\x33"].to_s

But we can have more fun than that (muhahaha...)

class Array
  def chr
    self.map { |e| e.chr }
  end
end

So then:

>> [1,2,3,65,66,67].chr
=> ["\001", "\002", "\003", "A", "B", "C"]
>> [1,2,3,65,66,67].chr.to_s
=> "\001\002\003ABC"
Comments