Python实现每隔固定时间读取数据

Python实现每隔固定时间读取数据

  由于实验要求,需要用已经获得的数据模拟传感器实时采样,因此需要研究一下怎么能每隔固定的时间读取一次数据。
  看网上的方法主要分为两种:

    1. 采用多线程+sleep函数+循环;
    2. 采用Timer类+循环。

由于此次实验需要每隔50msec采集一次数据,时间间隔较短,所以采用Timer类+循环。

import numpy as np
import math
import cv2
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import datetime

def get_data(f):
    global time

    point_64 = []

    for i in range(64):
        line = f.readline()
        a = line.split()
        d = ''

        for j in range(3, 11):
            b = bin(int(a[j], 16))
            c = b.replace('0b', '')
            zero_num = (len(a[j]) * 4) - len(c)
            if zero_num:
                for k in range(zero_num):
                    c = '0' + c
            d = d + c

        angle_B = d[11:21]
        range_B = d[21:32]
        range_rate_B = d[50:64]

        if angle_B[0] == '0':
            angle_D = -int(angle_B[1:], 2)/10
        else:
            angle_D = int(angle_B[1:], 2)/10

        range_D = int(range_B, 2)/10

        if range_rate_B[0] == '0':
            range_rate_D = -int(range_rate_B[1:], 2)/100
        else:
            range_rate_D = int(range_rate_B[1:], 2)/100

        # Polor to Cardesian
        # adjustment is to adjust the angle
        # adjustment = math.atan(2.5/50)
        adjustment = 0
        angle = angle_D + adjustment
        x = math.sin(math.radians(angle)) * range_D
        y = math.cos(math.radians(angle)) * range_D

        point = [x, y, range_rate_D]
        point_64.append(point)

    return point_64


file_name = 'data.txt'
f = open(file_name,'r')
time = datetime.datetime.now()

get_data(f)

while True:
    newtime = datetime.datetime.now()
    interval = (newtime - time).microseconds
    if interval >= 50000:
        print(interval)
        break

f.close()

运行结果如下:

50863

Process finished with exit code 0

上面的程序中gat_data不重要,主要是用最后面的一个while循环完成了每隔50msec读取并处理一次数据。但是最后还会剩下0.864毫秒,这是 while 和 if 语句运行的时间,想了半天不知道该怎么去掉,希望有大神来帮忙,5555555

  • 2
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值