milli() implementation and interrupts

Josh pointed out that the Arduino interrupt handlers were kinda inefficient.

I found this study on milli implementation.

I’m a bit surprised that the interrupt handler does the time fraction correction (a tick is 1.024ms or 3/125) instead of the time functions. However Nick Gammon’s tutorial on interrupt handers points out there’s a 5µsec overhead to run them. I was surprised they need to disable interrupts in milli(), but then again it’s an 8bit CPU so atomic accesses are only for bytes, not words or dwords.

Other notable infos:

  • AVR studio 6 has a simulator that can count runtime cycles. There’s tutorials on porting arduino’s environment.
  • micros() takes 49 cycles @16MHz, 3.06usec. Nick’s tutorial says micros() takes 3.5625 µS (57 cycles) and millis() takes 1.9375 µS (31 cycles).
  • The code uses a nifty reentrant interrupt disable trick which saves/restores the interrupt state:
    uint8_t oldSREG = SREG;
     cli();
    // do work
    SREG = oldSREG;
Any code that disables interrupts for more than 1ms will screw up the clock. Any event that can happen faster than 5µsec needs to use polling instead of interrupts. It’s also good to know.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s