How to measure loop rate

Hi all!

I’m currently working on an application using the SimpleFOC Drive Shield, trying to achieve a speed of 730 rad/s with a Moons ECU16036H12-S107&M16-1024 slotless BLDC.

Rather than just trying random things I really want to be able to measure and understand what is happening behind the scenes here, and one of the key variables for speed is the loop rate. But how do people usually measure the loop rate? Just by adding a timer to the Arduino loop function, then reporting that over Serial? But wouldn’t the Serial transfer result in a slower loop rate?

Keen to learn how this has been done by our resident FOC experts :star_struck:

At beginning of loop(), uint32_t start = _micros(). After motor.move and loopFOC, uint32_t end = _micros(). Then

static uint32_t lastPrintTime = 0;
if(millis() - timeSinceLastPrint > 500) {
  timeSinceLastPrint = millis();
  Serial.println(end - start);
}

Or if you want it in frames per second, Serial.println(1000000 / (end - start));

The printing does make this iteration of the loop take longer, but the reported number should be equal to the typical loop time.

Two approaches:

  1. what deku said: print the number of iterations per second by counting them and printing only once per second. Printing only once per second won’t significantly impact the loop time. The print should be buffered by the serial implementation so when you print only occasionally it won’t encounter blocking I/O.

  2. use digitalWrite() to toggle an IO pin once per iteration. Then attach your logic analyzer or a frequency counter to that pin and check the frequency with which it is toggling. This method should not impact performance significantly, and should be “constant time”, I.e will take the same (insignificant) amount of time each iteration and not introduce any jitter to your timings.