【问题标题】:Problem reading data from serial port in python从python中的串口读取数据的问题
【发布时间】:2011-03-21 03:58:55
【问题描述】:

我有一个 python 程序试图从一个串行端口读取 14 个字节 来得很慢。我想捕获所有字节 字节数组[14]。我了解 python 3.0 中有新的字节数组功能,但是 我只运行 python 2.6.6。升级可能会产生意想不到的后果,所以我不得不 坚持使用 2.6.6。

数据只是间歇性地流过串行端口。我收到一条消息 端口可能每 2 分钟左右。这些数据流动非常缓慢。我看到的问题是 我的代码不能一次可靠地读取一个字节的数据。我想把这个框起来 数据正好是 14 字节,然后处理数据并以新的 14 字节重新开始 字节。

我在这里采取了错误的方法吗?建议?

    ser = serial.Serial('/dev/ttyUSB1', 1200, timeout=0)
    ser.open()
    print "connected to: " + ser.portstr
    count=0
    while True:
        line =ser.readline(size=14) # should block, not take anything less than 14 bytes
        if line:
            # Here I want to process 14 bytes worth of data and have
            # the data be consistent.
            print "line(" + str(count) + ")=" + line
            count=count+1
    ser.close()

这就是我所期待的:line(1)=�0~888.ABC�/以回车结尾

---------开始输出------

line(0)=0
line(1)=~ ??1. ABC �    # here get some multiple bytes and stuff gets out of synch

�ine(2)=
line(3)=0
line(4)=~
line(5)= 
line(6)=8
line(7)=8
line(8)=8
line(9)=.
line(10)= 
line(11)=A
line(12)=B
line(13)=C
line(14)= 
line(15)=�
line(16)=

#...
line(48)=
line(49)=�
line(50)=0
line(51)=~
line(52)= 
line(53)=8
line(54)=8
line(55)=8
line(56)=.
line(57)= 
line(58)=A
line(59)=B
line(60)=C
line(61)= 
line(62)=�
line(63)=

line(64)=

---------结束输出------

【问题讨论】:

    标签: python serial-port device


    【解决方案1】:

    PySerial 的 API 文档说 readline() 一直读取到 \n,或者直到达到大小。但是,read() 函数表示它将阻塞直到达到大小。这两个函数都说如果设置了超时,它们会提前返回。

    Possible values for the parameter timeout:
    
    timeout = None: wait forever
    timeout = 0: non-blocking mode (return immediately on read)
    timeout = x: set timeout to x seconds (float allowed)
    

    也许试试timeout=None 而不是timeout=0

    【讨论】:

      【解决方案2】:

      试试这个:

      ser = Serial('/dev/ttyUSB1', 1200, timeout=0)
      print "connected to: " + ser.portstr
      count=0
      while True:
           for line in ser.readlines()   
                print "line(" + str(count) + ")=" + line
                count=count+1
      
      ser.close()   
      

      如果您还没有使用过line.strip() 函数,您可能也对它感兴趣。另外,强调ser.readlines() 中的s,与.readline() 不同。

      【讨论】:

        【解决方案3】:

        更改波特率。

        ser = serial.Serial('/dev/ttyUSB1', 9600, timeout=0)
        

        到兼容的波特率。

        获取 14 字节数据:

        data = ser.read(size=14)
        

        【讨论】:

        • 您建议不同波特率的理由是什么? OP 的示例显示接收到预期的数据(不是一次读取全部),这表明波特率是正确的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-18
        • 2012-10-14
        • 2017-09-06
        • 2018-04-18
        • 2021-06-04
        • 1970-01-01
        相关资源
        最近更新 更多