计算通过串口接收的两个连续数据包之间的时间的Python脚本

2 投票
4 回答
2188 浏览
提问于 2025-04-17 02:41

我正在调试我的代码,需要写一个Python脚本,来读取通过蓝牙发送的串口数据,并计算每个连续数据包之间的时间间隔。我知道怎么从串口读取数据,但在计算每个数据包之间的时间时遇到了问题。

任何建议都会很有帮助。

谢谢!

4 个回答

1

你可以试试这样做。创建一个 IntTimer() 对象,每当你收到一个数据包时,就调用它的 .stamp() 方法。这只是一个开始,如果它能满足你的需求,你可能还需要修改一下,以便清理旧的时间戳,否则 self.timestamps 会一直增加。你可以用 self.timestamps 来计算数据包之间的平均时间等等。

import time

class IntTimer:
    def __init__(self):
        self.timestamps = []

    def stamp(self):
        if self.timestamps:
            last = self.timestamps[-1]
        else:
            last = False

        now = time.time()

        self.timestamps.append(now)

        if last:
            #return the time since the last packet
            return now - last  
        else:
            return -1          

这个回答比较简单,如果你问的问题更复杂,记得告诉我哦。

1

你为什么不使用Python的time模块来计算时间差呢?如果你需要更精确的时间,你可以用select这个系统调用自己实现一个计时器。

不过,更好的办法是使用像Portmon这样的工具。

0

我会使用 time.time() 这个函数,然后通过减法来计算经过了多少秒。

import time

# receive one packet
t0 = time.time()
# then receive the other packet
t1 = time.time()

print 'Time between packets (seconds):', t1 - t0

撰写回答