Background timer [multithreading]

I need to start a timer when my photon (acting as a clinet) receives a signal via TCP.

The photon should keep track of time precisely, read via I2C IMU data (new data incoming every 0.01s) and read analog values from a pressure pad.

Since the timer need to be accurate to the milisec I was thinking of running it on its own thread but I cannot find any documentation on how to achieve this (nor I’m sure whether this could actually be done).

I am open to any other suggestions that can help me tackling this problem.
cheers

Just running on its own thread might not neccessarily give you the desired precission, but have a look at the IntervalTimer library which runs on timed interrupts.
https://build.particle.io/libs/568be2fb07d120fc16000662
https://github.com/pkourany/SparkIntervalTimer

Thanks a lot for the reply. You are really helping me out with my project!

My understanding of what you were saying is that I should use the SparkIntervalTimer in this way

IntervalTimer myTimer;
myTimer.begin(myfunction, 1000, hmSec);

This would call myfunction() after 0.5 sec.

I would like to store the time recorded from the timer in a variable. Is this possible?

@marcodat, given that SparkIntervalTimer will create a true interrupt, I would recommend against doing hardware resource specific calls within the ISR, specifically doing I2C calls. You could do the I2C sampling in loop() given that sampling is done at 100ms intervals.

I think before you begin, having a timing/state diagram of each step would be great for understanding what you are trying to achieve. :wink:

thank for the reply. i implemented a pseudo-state diagram to explain what I would need to implement.

@marcodat, from what I see, there are two key timing requirements. The first is to start a “reliable and accurate” millisecond timer that can started, stopped and read. The second is a 100ms timer which is used to trigger I2C data collection from the mpu6050.

The first timer can be created using SparkIntervalTimer with a simple counter in the ISR. The second is dependent on the timing accuracy needed. This could be as simple as a 100ms millis() non-blocking timer. Sending data to the server at that rate should not be a problem assuming it is straight TCP or UPD data. Can you elaborate?

1 Like

I can, thank you a lot for your support!

Just a note for future reference: to set the second timing interval (ie the dmp’s sampling rate) setRate() can be used in the MPU6050_6Axis_MotionApps20.h
This sets the sampling frequency of the MPU6050 and it’s better changing this parameter rather the interrupt frequency to avoid FIFO buffer overflow.

@marcodat if I understand correctly, the mpu6050 will generate it’s own interrupts or will you be polling it?

@peekay123 that’s correct, the mpu6050 generates its own interrupts.