Pyserial能够在Shell中运行良好,但是在脚本中运行失败

简单地说,就是同一段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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值