python - pySerial 非常奇怪的行为...代码在 shell 中执行时有效,但在脚本中无效

标签 python pyserial

我正在与 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)

关于python - pySerial 非常奇怪的行为...代码在 shell 中执行时有效,但在脚本中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35878750/

相关文章:

Python:将名称列表划分为大小相等的子列表

python - py安装程序: qwebkit cannot load pictures and garbled text when package pyside gui with pyinstaller

python - 在Python中对分组条形图按一定顺序对x轴进行排序

python - 如何访问使用 django 的社交身份验证生成的 token ?

python - 在 python 中将蓝牙设备与密码/密码配对 - RFCOMM (Linux)

python - PySerial 与变量的通信

Python:pyserial 超时似乎不适用于连接

python - 将 RFC2217 网络串行端口与 Twisted Python 一起使用?

python - PySerial 无法识别或发现串行端口

python - 绘图时使用 pySerial 读取实时值