2

I'm using this piece of code to try to poll an IMU sensor at 100 Hz (for a AHRS sensor fusion library).

void loop(void)
{
  // nonblocking code variables
  static uint32_t last_ms;
  uint32_t ms;
  // delay between samples
  ms = millis();
  if (ms - last_ms < 10) return;
  last_ms = ms;

sensor_data (); //...

My 1st question is should I be declaring last_ms as a global variable instead of static?

Also, should this code be at the beginning or end of loop? My understanding is we are basically checking how long the previous loop took. And if it took less than 10 ms (100 Hz) we do nothing. But doesn't that mean that we might still get deviation from 100 Hz due to the time it takes to complete loop (about 2-5ms in my case), so effectively it's 10 ms + loop complete time?

Sorry if this is a stupid question.

Zhelyazko Grudov
  • 367
  • 1
  • 13
  • see the BlinkWithoutDelay example. I guess it is easy to modify it from 1 Hz to 100Hz – Juraj Jun 22 '21 at 11:47
  • 3
    If you want to run something at 100Hz you probably want to use a timer interrupt rather than fiddling with delay values. – Dave Newton Jun 22 '21 at 12:19
  • I will experiment with that thank you – Zhelyazko Grudov Jun 22 '21 at 12:44
  • 1
  • static/global; meh, same thing really. 2. it should be 100Hz since you restart the clock before running the task, so it won't jitter unles the task takes longer than 10ms, but if that's the case there's no way it will ever work anyway.
  • – dandavis Jun 22 '21 at 19:11
  • Can you configure this particular device to use interrupts rather than polling? – ScottishTapWater Jun 23 '21 at 13:43
  • it's the BMX160 from Bosch, and I think so. I will experiment with that, but wanted to understand logic of this also. – Zhelyazko Grudov Jun 23 '21 at 17:59