How to count time when interrupts are disabled?

Status
Not open for further replies.

marcmerlin

Well-known member
I have code like this
before = millis()
leds.show() (using adafruit neopixel or FastLED libraries)
Serial.println(millis() - before)

Because both libraries when they talk to neopixels, have to disable interrupts for some amount of time, millis() does not increment, and therefore I get the wrong value back.
Using micros() is supposed to use CPU counters, but does not work better in my testing.

Is there another way to get time elapsed in that case? (if possible in a way that works on other processors too)

Thanks.
 
Code:
    //Enable ARM-M4 Cycle Counter
    ARM_DEMCR |= ARM_DEMCR_TRCENA;
    ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;

then
Code:
unsigned cycles = ARM_DWT_CYCCNT;
gives you the cpu-cycles spent. This works on any ARM Cortex M (and I think on other ARMs, too).

This counter really counts cycles, so, for 120MHZ, it will increase 120000000 times every second and quickly overflow.
 
Last edited:
Code:
unsigned cycles = ARM_DWT_CYCCNT;
gives you the cpu-cycles spent. This works on any ARM Cortex M (and I think on other ARMs, too).
Not quite, not all Cortex M0 have it - Teensy LC doesn't. Teensy 3.x does.
 
No.
Even it was possible - if you return from your "reset counter" function, it will again have several dozen counts... ;-)
So why should you want to do that ? Resetting is not the usual way to work with such counters.. and it can interfere with other code that uses this counter (for example, the audio-library)
Normally, you use a difference.

aka

cyles = ARM_DWT_CYCCNT;
/* dowhateveryouwanthere */
spentcycles= ARM_DWT_CYCCNT - cycles;
 
Last edited:
Status
Not open for further replies.
Back
Top