我正在尝试使用ruby对串口进行简单的读写操作.
这是我到目前为止的代码.我正在使用serialport宝石.
require 'rubygems'
require 'serialport'
ser = SerialPort.new("/dev/ttyACM0", 9600, 8, 1, SerialPort::NONE)
ser.write "ab\r\n"
puts ser.read
Run Code Online (Sandbox Code Playgroud)
但是脚本在运行时会挂起.
我遇到了问题.这是因为使用ser.read告诉Ruby永远继续阅读,Ruby永远不会停止阅读,从而挂起脚本.解决方案是只读取特定数量的字符.
例如:
ser.readline(5)
Run Code Online (Sandbox Code Playgroud)
小智 5
为了回应 user968243 所说的,该 ser.read 调用将等待 EOF。如果您的设备没有发送 EOF,您将永远等待。您只能按照建议读取一定数量的字符。
您的设备可能会以行尾字符结束每个响应。尝试读取到下一个回车符:
response = ser.readline("\r")
response.chomp!
print "#{response}\n"
Run Code Online (Sandbox Code Playgroud)