Ruby – Reading from a Serial Port with Ruby

rubyserial-port

I'm trying to use ruby to do a simple read + write operation to a serial port.

This is the code I've got so far. I'm using the serialport gem.

require 'rubygems'
require 'serialport'

ser = SerialPort.new("/dev/ttyACM0", 9600, 8, 1, SerialPort::NONE)

ser.write "ab\r\n"
puts ser.read

But the script hangs when it is run.

Best Answer

I had the problem to. It's because using ser.read tells Ruby to keep reading forever and Ruby never stops reading and thus hangs the script. The solution is to only read a particular amount of characters.

So for example:

ser.readline(5)