Help With Slow Loop Time (stm32-f446re)

Hello,

I recently got my SimpleFOC board working with a nucleo board and I’m learning that updates rates are going to be really important to my application. I threw some micros() calls in my loop to see what I should optimize, but the code in the loop is only 1/10th the duration of each loop cycle. Here’s a slightly simplified example of my test:

void loop() {
  long now = micros();
  long loopDelta = now - lastLoopTime;
  lastLoopTime = now;

  Serial.print("loopDelta: ");
  Serial.print(loopDelta);
  Serial.print("\n");

  long focStart = micros();
  // iterative setting FOC phase voltage
  motor.loopFOC();

  float localAngle = sensor.getAngle();

  float delta = (target - localAngle);

  // iterative function setting the outter loop target
  motor.move(delta);
  long focEnd = micros();
  Serial.print("foc: ");
  Serial.println((focEnd - focStart));
 
  long serialStart = micros();
  if (Serial.available()) {
    // change the role via the serial monitor
 
    char c = toupper(Serial.read());
    if (c == 'S') {
      stopped = true;
    }
  }
  long serialEnd = micros();
  Serial.print("serial: ");
  Serial.println((serialEnd - serialStart));
}

Please forgive the sloppy naming. The gist is that I’m timing the following:

  • How long the SimpleFOC calls take
  • How long the Serial calls take
  • How long it’s been since the last time the loop ran

Surprisingly, SimpleFOC takes about 200us, Serial takes about 1us, but the loop time (or loopDelta) is 1500-6000us.

So stuff that is invisible to me is dropping my update rate from ~5khz to ~266hz. Does anyone have any hints on what might be going on? I’m pretty new to embedded programming so I’m not sure where to start. Is there a way to profile what’s going on in the background? Am I just measuring things incorrectly? Will I need to make the leap to STM32CubeIDE to get good performance? Any help would be appreciated.

Oh and I’m using platformio if that matters.

Maybe your sensor is slow, it’s hard to tell since you don’t give the full picture here.

Could you try to count the loops per second instead of messing up each loop with all that serial jippering ?

1 Like

Try not to print with every loop. Instead, do some averaging over let’s say 5s and then print the result every 5s. Serial.print() may be very slow.

/Chris

1 Like

Hi,

You’re timing the time needed for serial input (very low, unless you’re sending commands at a fantastic high rate), but not serial output.

So as @Grizzly says, you’re outputting too much to serial. Once the serial buffer is full the calls to println() will block until the Serial port has has a chance to flush some data.

If you output only once per second, things will improve a lot.

Please be sure to include the option

lib_archive = false

to your project’s platformio.ini file.

1 Like

Oh yep, it was just too much Serial activity. The loop is running at a sensible speed now. Thanks everyone!