【问题标题】:How to quickly read single byte serial data using Python如何使用 Python 快速读取单字节串行数据
【发布时间】:2014-09-24 05:03:20
【问题描述】:

我正在使用以下代码在 Python 中读取串行数据:

port = "COM11"
baud = 460800
timeout=1

ser = serial.Serial()
ser.port = port
ser.baudrate = baud
ser.timeout = timeout
while 1:
     # Read from serial port, blocking
     data =ser.read(1)
     print data
     # some further processing of data

我正在以非常快的速度发送数据,但是当我使用此代码时,我以非常慢的速度获取数据,可能每秒大约 2 到 3 个数据。这太慢了,因为我想做实时绘图。

所以,我尝试了上面的代码,而不是:

 while 1:
     # Read from serial port, blocking
     data =ser.read(1)
     data1=(data)


     # If there is more than 1 byte, read the rest
     n = ser.inWaiting()
     data1 = (data1 + ser.read(n))
     print data1

现在数据更新的速度是相同的,但不是单个字节,而是我检查输入队列中的多个字节并读取它们。我每个循环接收大约 3850 个字节,所以这个对我来说似乎要快得多,但实际上几乎相同,唯一的变化是我没有读取更多字节。

我想读取一个字节并检查它的接收时间。为此,我不能使用使用ser.inWaiting() 的第二种方法。我怎样才能比使用上述方法更快地读取单字节数据?

【问题讨论】:

  • 可能想参考这个帖子的答案:stackoverflow.com/questions/19908167/…
  • 是的,我已经看到了,他们只是建议使用 ser.read() 而不是 ser.readline() 并使用 ser.inWaiting()。我已经在做所有这些事情了。我无法足够快地读取数据
  • 当您使用较低的波特率时会发生什么?
  • 你必须打开和关闭串口。

标签: python pyserial


【解决方案1】:

这是我为一个项目编写的一些测试代码,您可以尝试不同的波特率设置。基本上,它会在 Tx 上发送一些数据(可以直接连接到 Rx),并期望这些数据被回显。然后它将返回的数据与发送的数据进行比较,并让您知道是否/何时发生错误。请注意,如果没有错误,则输出将保持空白,并且在测试结束时将打印“0 Comm Errors”。

import serial, time

test_data = "hello this is so freakin cool!!!" + '\r' #Must always be terminated with '\r'
echo_timeout = 1 #the time allotted to read back the test_data string in seconds
cycleNum = 0
errors = 0
try:
        ser = serial.Serial(port="COM1", baudrate=115200, timeout=1)
        ser.flush()
        print "starting test"
        for x in xrange(100):
                cycleNum += 1
                d = ser.write(test_data)
                ret_char = returned = ''
                start_time = time.time()
                while (ret_char <> '\r') and (time.time() - start_time < echo_timeout):
                        ret_char = ser.read(1)
                        returned += ret_char
                if not returned == test_data:
                    errors += 1
                    print "Cycle: %d Sent: %s Received: %s" % (cycleNum, repr(test_data), repr(returned) )
except Exception as e:
        print 'Python Error:', e
finally:
        if 'ser' in locals():
                print "%d Comm Errors" % errors
                if ser.isOpen():
                        ser.close()
                        print "Port Was Successfully Closed"
                else:
                        print "Port Already Closed"
        else:
                print "Serial Variable Was Never Initialized"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2021-02-09
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    相关资源
    最近更新 更多