PWM driver initialization changes Arduino timer behavior

I encounter an apparent bug when attempting to measure time using millis or micros after initializing a PWM driver. On an Arduino Uno with the minimal code below, the results from millis are correct. However, if the driver.init() is uncommented, the results from millis are way too large - by a factor of about 32. What is going on here?

#include <SimpleFOC.h>

BLDCDriver3PWM driver = BLDCDriver3PWM(5, 9, 6, 8);

unsigned long time_now;

void setup() {

void loop() {

Update: The millis and micros results are correct if the driver is initialized with pins 3,10,11 instead of 5,9,6. I believe the unexpected behavior arises because pwm pins 5 and 6 are driven by timer0 which is the same timer that millis and micros are dependent on. In hardware_api.h, the _pinHighFrequency function changes the timer0 prescaler to 1 if pin 5 or 6 is used as a driver pin. Apparently, this change effectively scales the output of micros() and millis() by a factor of 32. As the article below warns - “The Arduino uses Timer 0 internally for the millis() and delay() functions, so be warned that changing the frequency of this timer will cause those functions to be erroneous.” My concern is that micros() is then also used in other parts of the library, such as sensor::getVelocity(), so this probably affects the velocity and position control loops if you have 5 or 6 as driver pins.

Hey @Caleb_Rucker,

This is true.
We have created the wrapper functions that ate safe to use: _delay() and _micros().
We did not make millis implementation sunce we don’t use it much :slight_smile:

Ah, I see that now. I did not notice the underscore in front of micros before. Sorry for the trouble, and thanks!