pySerial very strange behaviour … Code works when executed in shell but not in a script

喜夏-厌秋 提交于 2019-12-07 22:38:15

问题


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


回答1:


From the 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)



来源:https://stackoverflow.com/questions/35878750/pyserial-very-strange-behaviour-code-works-when-executed-in-shell-but-not-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!