Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get more precise time measures with a Raspberry Pi?

Recently I am developing a device base on raspberrypi 2b+ which connected to mpu9250(welding by myself).

I could read 9-axis data correctly, but I noticed that each data input with different time differential:

the figure shows the time differential between each two data. But I have used QTimer to make sure my code every 10ms reading mpu9250 once.

So I tried this code on RaspberryPi 2b+:

import time
import matplotlib.pyplot as plt

time_arr = []
for i in range(5000):
    t0 = time.time()
    print "K"
    t1 = time.time() - t0
    time_arr.append(t1)

plt.plot(time_arr)
plt.show()

And result:

enter image description here

even these simple code still shows peaks on diagram, and it's put me down...

Could anyone helps me solve these issue or explains what's going on?

like image 392
Mike Chan Avatar asked Nov 08 '22 07:11

Mike Chan


1 Answers

In your first test you are using QTimer which treats the timer as a background task. QT is primarily focused on providing a responsive GUI.

In your second test you have a print statement in the loop -- there are any number of factors involved in printing that can cause a variation in the time needed to execute the statement.

Take a look at the threading.Timer class for a better approach.

The documentation says:

This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.

Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method.

Note that it also says:

The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user.

In other words, it won't be perfect, but it is quite likely to be significantly better than what you are seeing now.


If you are interested in MEASURING time with higher precision as opposed to scheduling tasks with better precision, consider using time.perf_counter() which is available in Python 3.

like image 71
Dale Wilson Avatar answered Nov 14 '22 23:11

Dale Wilson