Atmel / AVR DISCUSSION

How should an 8-bit AVR read a counter updated by an interrupt?

Started by devarajhd AVR interruptsatomic accessshared countersvolatileconcurrency
3 replies 248 views 4 participants
Latest activity · 27 Sep 2026

How should an 8-bit AVR read a counter updated by an interrupt?

devarajhd Atmel / AVR Forum
#1

A main loop reads a 16-bit counter while an interrupt increments it on an 8-bit AVR. Why can an occasional reading appear to jump backward or forward even when the variable is declared volatile?

What is a small, predictable way to obtain a consistent snapshot?

Community replies 3

Re: How should an 8-bit AVR read a counter updated by an interrupt?

#2

Volatile controls relevant compiler access behavior; it does not make a multi-byte access indivisible. If the interrupt updates the counter between the main loop's byte reads, the result can combine bytes from different values. The failure may be rare and concentrated around a low-byte rollover.

Re: How should an 8-bit AVR read a counter updated by an interrupt?

#3

Copy the shared value inside a short critical section using the toolchain's supported mechanism, preserving the previous interrupt-enable state. Perform calculations and formatting on the local copy after leaving the critical section. Do not hold interrupts disabled while printing or waiting for a peripheral.

Re: How should an 8-bit AVR read a counter updated by an interrupt?

#4

Inspect the generated code and the exact variable width when diagnosing the problem. Also consider writes and read-modify-write operations, which need their own synchronization policy. Test rollover boundaries deliberately and account for the critical section in the timing budget of other interrupt-driven tasks.

TEP COMMUNITY