Pi上每隔n毫秒调用一次Python Timer2调用函数

时间:2016-11-04 15:11:41

标签: python timer scheduler

我在Python中使用timer2每隔10毫秒(100Hz)将数据从IMU传感器保存到文件中。我告诉timer2使用方法“apply_interval”每10毫秒运行一次该函数。 但是,时间戳显示该函数被不正确地调用太多次(每毫秒1次)

我需要以相同的精确间隔保存数据,以便执行机器学习。

如果你能和我一起解决,我会很高兴的。

以下是代码:

from numpy import linalg as LA
from conf import *
import RTIMU
from ledFunctions import *
import timer2

class IMU():

def retrieve_data(self):
    t = time.time()
    timestamp = t - self.last_time
    self.last_time = t

    accel = self.data["accel"]
    gyro = self.data["gyro"]
    mag = self.data["compass"]
    f = open(self.nameFile, "a")

    f.write(str(accel[0]) + ";" + str(accel[1]) + ";" + str(accel[2]) + ";" +
    str(gyro[0]) + ";" + str(gyro[1]) + ";" + str(gyro[2]) + ";" +
    str(mag[0]) + ";" + str(mag[1]) + ";" + str(mag[2]) + ";" + str(timestamp) + "\n")

    f.flush()
    f.close()

def __init__(self):
    self.last_time = time.time()
    print("Using settings file " + SETTINGS_FILE + ".ini")
    if not os.path.exists(SETTINGS_FILE + ".ini"):
        print("Settings file does not exist, will be created")

    self.s = RTIMU.Settings(SETTINGS_FILE)
    # Create IMU object
    self.imu = RTIMU.RTIMU(self.s)

    print("IMU Name: " + self.imu.IMUName())

    # Init IMU
    if (not self.imu.IMUInit()):
            print("IMU Init Failed")
            sys.exit(1)
    else:
            print("IMU Init Succeeded")

    # This is a good time to set any fusion parameters

    self.imu.setSlerpPower(0.02)
    self.imu.setGyroEnable(True)
    self.imu.setAccelEnable(True)
    self.imu.setCompassEnable(True)

    # Check if save directory exists
    self.imuDir = ifDirExists(imuDirectoryName)

    nameFileNum = self.imuDir + "/nb"
    # Check if nb file exists
    if not (os.path.isfile(nameFileNum)):
        fnb = open(nameFileNum, "w")
        fnb.write(str(0))
        fnb.flush()
        fnb.close()
        nb = 0
        print("nb file does not exist, create it")
    else:
        fnb = open(nameFileNum, "r")
        nb = int(fnb.readline().strip())
        fnb.close()
        print("nb file exists")

    # Create new file with name = nb + 1
    nb = nb + 1
    self.nameFile = self.imuDir + "/" + str(nb) 
    try:
        f = open(self.nameFile, "a")
        # Increment the value in nb file
        fnb = open(nameFileNum, "w")
        fnb.write(str(nb))
        fnb.flush()
        fnb.close()

        self.lastDisplay = time.time()
        self.poll = self.imu.IMUGetPollInterval()
        self.deltat = 0
        self.now = self.lastDisplay = time.time()
    except IOError as e:
        print "I/O Error({0}): {1}".format(e.errno, e.strerror)

    # Retrieve data when available
    if self.imu.IMURead():
        self.data = self.imu.getIMUData()
    timer2.apply_interval(100, self.retrieve_data)

def loop(self):
    # Retrieve data when available
    if self.imu.IMURead():
        self.data = self.imu.getIMUData()

Thx:)

0 个答案:

没有答案