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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With