我正在为 pySerial 苦苦挣扎。简而言之...下面的代码在 Python Shell 中执行时效果很好...
>>> import serial
>>> s=serial.Serial("COM5", 9600)
>>> while(1):
s.write("#")
s.readline()
在 shell 中生成以下输出:
1L
'56.73\r\n'
1L
'56.73\r\n'
当在脚本中写入相同的代码时说“readSerial.py”,脚本将不会传输触发串行设备传输数据的标签,或者不会接收回复的数据。
我正在使用 pySerial 3,但我注意到 2.7 的行为相同。在 Win10 上使用 Python 2.7.10 64 位。但也注意到 Raspberry Pi 上的这种行为/dev/ttyACM0。我真的很想解决这个问题。我在 Python 方面经验不足,所以这可能是一个疏忽。
硬件经过反复检查。
谢谢,
KK
谢谢,但我真的知道如何从 Python 打印数据。问题确实出在 pySerial 上。这是完整的代码,请不要讨论注释掉的代码中的错误。这些在这里都无关紧要。
#from numpy import array
#import matplotlib.animation as animation
import time
import serial as s
#data = array([])
Arduino = s.Serial("COM5", 9600)
i = 0
while (1):
try:
Arduino.write("#")
time.sleep(.1)
inString = Arduino.readline()
data = float(inString)
print i, ":", data
i += 1
time.sleep(1)
except KeyboardInterrupt:
break
Arduino.close()
但是就像说的那样,这是行不通的。据我所知,readline() 函数没有返回。而且...通过设置 tx 超时让它返回真的没有意义。增加神秘感;当代码被调试时(即逐步执行)它确实有效。
提前致谢
KK
请您参考如下方法:
来自FAQ :
Example works in serial.tools.miniterm but not in script.
The RTS and DTR lines are switched when the port is opened. This may cause some processing or reset on the connected device. In such a cases an immediately following call to write() may not be received by the device.
A delay after opening the port, before the first write(), is recommended in this situation. E.g. a time.sleep(1)
