Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a Serial Port with Ruby

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.

like image 353
psp Avatar asked Jun 15 '11 10:06

psp


5 Answers

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)
like image 87
Jean-Luc Avatar answered Oct 05 '22 03:10

Jean-Luc


To echo what user968243 said, that ser.read call is going to wait for EOF. If your device is not sending EOF, you will wait forever. You can read only a certain number of characters as suggested.

Your device may be ending every response with an end of line character. Try reading up to the next carriage return:

response = ser.readline("\r")
response.chomp!
print "#{response}\n"
like image 37
Hubcity Avatar answered Oct 05 '22 04:10

Hubcity


I ran into this same problem and found a solution. Use the Ruby IO method readlines.

puts ser.readlines
like image 32
Nolan Avatar answered Oct 05 '22 02:10

Nolan


Maybe your device is waiting for some input. Check this answer and see if it helps: https://stackoverflow.com/a/10534407/1006863

like image 43
Paulo Fidalgo Avatar answered Oct 05 '22 02:10

Paulo Fidalgo


Try setting the #read_timeout value for the serial port. Note that the same thing can be done for a write operation using the #write_timeout value.

like image 25
Norbert Lange Avatar answered Oct 05 '22 04:10

Norbert Lange