在 Python 中实时读取串行数据 [英] Reading serial data in realtime in Python

查看:32
本文介绍了在 Python 中实时读取串行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 脚本通过串行端口以 2Mbps 的速度从 PIC 微控制器收集数据.

I am using a script in Python to collect data from a PIC microcontroller via serial port at 2Mbps.

PIC 以 2Mbps 的完美时序工作,FTDI usb 串行端口也以 2Mbps 的速度工作(均用示波器验证)

The PIC works with perfect timing at 2Mbps, also the FTDI usb-serial port works great at 2Mbps (both verified with oscilloscope)

我以每秒 100-150 倍的速度发送消息(大约 15 个字符的大小),并且数量会增加(检查我是否有消息丢失等)

Im sending messages (size of about 15 chars) about 100-150x times a second and the number there increments (to check if i have messages being lost and so on)

在我的笔记本电脑上,我将 Xubuntu 作为虚拟机运行,我可以通过 Putty 和我的脚本(python 2.7 和 pySerial)读取串口

On my laptop I have Xubuntu running as virtual machine, I can read the serial port via Putty and via my script (python 2.7 and pySerial)

问题:

  • 当通过 Putty 打开串行端口时,我会看到所有消息(消息中的计数器以 1 递增 1).完美!
  • 当通过 pySerial 打开串行端口时,我看到所有消息,但不是每秒接收 100-150x,而是以大约每秒 5 次接收它们(消息仍以 1 递增 1),但它们可能存储在某个缓冲区中我关掉 PIC 的电源,我可以去厨房然后回来,我仍然在接收消息.

代码如下(我省略了大部分代码,但循环是一样的):

Here is the code (I omitted most part of the code, but the loop is the same):

ser = serial.Serial('/dev/ttyUSB0', 2000000, timeout=2, xonxoff=False, rtscts=False, dsrdtr=False) #Tried with and without the last 3 parameters, and also at 1Mbps, same happens.
ser.flushInput()
ser.flushOutput()
While True:
  data_raw = ser.readline()
  print(data_raw)

有谁知道为什么 pySerial 需要花费如此多的时间从串口读取数据直到行尾?有什么帮助吗?

Anyone knows why pySerial takes so much time to read from the serial port till the end of the line? Any help?

我想实时拥有这个.

谢谢

推荐答案

您可以使用 inWaiting() 获取输入队列中可用的字节数.

You can use inWaiting() to get the amount of bytes available at the input queue.

然后你可以使用 read() 来读取字节,就像这样:

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

为什么不使用 readline() 在这种情况下来自文档:

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

您在每次读取时都在等待超时,因为它等待 eol.串行输入 Q 保持不变,只是需要很多时间才能到达缓冲区的末尾",为了更好地理解它:您像赛车一样写入输入 Q,像旧车一样读取 :)

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

这篇关于在 Python 中实时读取串行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆