Michał Jonik
2010-02-08 · archive

AVR programming caveats

Archived post from 2010, recovered from my old blog. The technology described here is probably out of date. Original at the Internet Archive.

During development of my prototype modules for intelligent home a couple of times I stuck trying to find a nasty bug hiding somewhere and stealing precious hours of my sleep. Sometimes I needed a couple of hours to figure out the cause. Another time it took a couple of days and made me furious.

I’d like to share here the two caveats of low level C programming that were a source the most difficult issues. Both relate to GCC compiler but do not necessary confine to AVR family.

Interrupt service routines

The compiler makes sure that all the registers used inside interrupt service routine (ISR) will be stored before and restored after execution of ISR. However it relates only to registers used directly inside ISR code and does not relate to registers used by other routines called by an ISR. That can lead to unpredictable behaviour and difficult to diagnose issues.

There are at least a few solutions:

  • do not call other routines from ISR code
  • manually store and restore (all?) registers using in-line assembler in ISR
  • make sure a subroutine called from ISR code does not change any registers other then those returning results

Global register variables

One of the trick to optimize size and performance of low level C programs is to use global register variables for most often used variables.

When a global variable is declared as a register variable the compiler does not use this register for any other purposes. Unfortunately it applies only to that compilation unit where the variable was defined. The compiler doesn’t know anything about reserved registers when compiling other compilation units. As a result the product of linking these units may introduce hard to trace problems.

To avoid that issue a register variable should be declared in all compilation units to be linked together including external libraries.

avrcgccisr