开发者

Python script to calculate the time between 2 successive packets received over the serial port

I am debugging my code for which I need to write a python script that can read data being sent over the serial port through bluetooth and calculate the time el开发者_JAVA技巧apsed between each successive packet.I know how to read the data from the serial port but I am having issues with calculating the time between each packet.

Any suggestions would be very helpful.

Thanks!


Something like this might do the trick. Just create a IntTimer() object and call .stamp() on it whenever you receive a packet. It's just a start, so if it does what you want then you might need to change it to clean up the old stamps etc., otherwise self.timestamps will just grow and grow. You could use self.timestamps to work out average times etc. between packets.

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          

This is quite a simple answer, so if you're asking a more complicated question then do say so.


Why don't you use python time module to calculate time diff? If you need beter precision you can implement your own timer using the select system call.

But a better solution is to use something like Portmon


I would use time.time() and subtract to find the number of seconds elapsed.

import time

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

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


So this is what I wrote and it worked.Thank you all for your answers.

#!/bin/python

import serial
import time


time_stamp_prev = 0

ser = serial.Serial(  \
    port="/dev/tty.bluetoothmodule", \
    baudrate=115200, \
    parity=serial.PARITY_NONE, \
    stopbits=serial.STOPBITS_ONE, \
    bytesize=serial.EIGHTBITS )

while True:
    if ser.inWaiting() > 0:


    print ser.readline();
            time_stamp_curr = time.time()
            time_between_packets = time_stamp_curr - time_stamp_prev
            time_stamp_prev = time_stamp_curr
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜