问题描述
我正在为 pySerial 苦苦挣扎.简而言之......下面的代码在 Python Shell 中执行时效果很好......
>>>导入序列>>>s=serial.Serial("COM5", 9600)>>>同时(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 位.但也注意到了树莓派/dev/ttyACM0 上的这种行为.我真的很想解决这个问题.我在 Python 方面没有经验,所以这可能是一个疏忽.
硬件经过检查和双重检查.
谢谢,
KK
谢谢,但我真的知道如何从 Python 打印数据.问题确实出在 pySerial 上.这是完整的代码,请不要讨论注释掉的代码中的错误.这些在这里都无关紧要.
#from numpy 导入数组#import matplotlib.animation 作为动画导入时间导入序列为 s#data = 数组([])Arduino = s.Serial("COM5", 9600)我 = 0而(1):尝试:Arduino.write("#")时间.睡眠(.1)inString = Arduino.readline()数据 = 浮点数(输入字符串)打印 i, ":", 数据我 += 1时间.睡眠(1)除了键盘中断:休息Arduino.close()
但是就像说这行不通.据我所知, readline() 函数没有返回.而且……通过设置 tx 超时来让它返回真的没有意义.增加神秘感;当代码被调试(即阶梯式低谷)时,它确实可以工作.
提前致谢,
KK
来自 FAQ :
示例在 serial.tools.miniterm 中有效,但在脚本中无效.
RTS 和 DTR 线在端口打开时切换.这可能在连接的设备上引起一些处理或重置.在这样一个可能无法收到紧随其后的 write() 调用的情况设备.
打开端口后,第一次 write() 之前的延迟是在这种情况下推荐.例如.a time.sleep(1)
I'm struggling with pySerial. To be brief ... The code below works great when executed in the Python Shell ...
>>> import serial
>>> s=serial.Serial("COM5", 9600)
>>> while(1):
s.write("#")
s.readline()
Produces the output below in the shell:
1L
'56.73\r\n'
1L
'56.73\r\n'
When the same code is written in a script say "readSerial.py" the script will either not transmit the hashtag that triggers the serial device to transmit the data, or will not receive the replied data.
I'm using pySerial 3, but have noticed the same behavior with 2.7. Using Python 2.7.10 64 bit on Win10. But also noticed this behavior on Raspberry Pi with /dev/ttyACM0. I would really like to have this solved. I'm not that experienced in Python so this might be an oversight.
Hardware is checked and double checked.
Thanks,
KK
Thanks, but I really know how to print data from Python. The problem is really with pySerial. Here is the complete code, please don't discus errors in commented out code. These are of no concern here.
#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()
But like said this doesn't work. As far as I can tell the readline() function does not return. And ... there 's really no point in making it return by setting the tx timeout. To add to the mistery; When the code is debugged (i.e. stepped trough) it does work.
Thanks in advance,
KK
From the FAQ :
这篇关于pySerial 非常奇怪的行为......代码在 shell 中执行时有效,但在脚本中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!