简单地说,就是同一段pyseial程序,在python 敲一遍能行,写到script 中执行就不行了!
心急的直接看5
开发环境:
操作系统: Windows 7 旗舰版 (64位)
编程环境 : Python 2.7.11 (64位)
pyserial-3.0.1
开发板 :Arduino UNO
Arduino 1.6.6 (http://www.arduino.cc/)
问题描述:
要实现Arduino与电脑利用pyserial进行串口通信!
1、Ardunio 程序是完整的可用的,用Arduino IDE 的串口监视测试是正常的!
2、python程序也是完整可用,利用虚拟串口VSPD和串口调试助手,测试正常!
测试代码:
import serial
ser = serial.Serial()
ser.port = "COM7"
ser.open()
re = ser.write("0")
s = ser.read(10)
print s
ser.close()
3、但是当直接与物理串口通信时就不行了!
没有设置timeout 所以一直阻塞,设置了timeout也收不到数据;这时候就得在任务管理里结束进程,有pythonw就选内存占用最少的那个
4、但同样的代码在python shell却行得通!
5、折腾了一两个小时,最后在Stackoverflow 找到解决方案:
import serial
import time ####################
ser = serial.Serial()
ser.port = "COM7"
####################
time.sleep(1)
ser.dtr = False
time.sleep(1)
####################
ser.open()
re = ser.write("0")
s = ser.read(10)
print s
ser.close()
截图如下:
原回答中是
time.sleep(1)
ser.setDTR(level=0)
time.sleep(1)但是在 pyserial 3.0 以后的版本 setDTR已经移除,参考 pyserial docs ,改成上文形式,证实可行!
附上链接:
1、pyserial : http://pyserial.readthedocs.org/en/latest/pyserial_api.html#serial.Serial.open
2、Arduino 与 Python : http://playground.arduino.cc/Interfacing/Python
3、Stackoverflow 解决方案 : http://stackoverflow.com/questions/2301127/pyserial-app-runs-in-shell-by-not-py-script/35908067#35908067
本文介绍了一个关于使用PySerial在Python脚本中与Arduino进行串口通信的问题,并提供了一个有效的解决方案,通过调整DTR信号来确保脚本可以正确运行。

7万+


被折叠的 条评论
为什么被折叠?



