简体   繁体   中英

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.

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)

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"

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

puts ser.readlines

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM