pin 20101high bytelow bytehigh byte0x00low byte0x001volatile uint16_t presses = 0;2void onPress() { presses++; }3void loop() {4 noInterrupts();5 uint16_t n = presses;6 interrupts();7 Serial.println(n);8}+1000103FF13511255256
Back: the button, the chip with its I bit, INT0 flag, register n and the two SRAM bytes of pressesFront: the firmware card and the Serial MonitorTokens: a press, the ISR's +1, single bytes, the printed nAn Arduino Uno R3: a button on pin 2 runs the ISR onPress(), which adds 1 to the shared variable presses in SRAM, while loop() copies it into a register and prints it. Without volatile the copy can go stale. And because the 8-bit CPU reads the two bytes of presses one at a time, an interrupt between them turns 255 into 511. Turning interrupts off for the copy keeps it whole; the waiting ISR runs right after.

One variable, two writers

  1. A button on pin 2 is wired to an interrupt. Each press sets the INT0 flag, pauses loop() and runs onPress(), the interrupt service routine (ISR). It adds 1 to presses, a global variable in SRAM, the chip's working memory.

volatile

Reading it whole

What happens

;; step 1/9 · isr-writes
pin 2       button to GND, falling edge = press
INT0       sets the flag INTF0, the CPU jumps to onPress()
line 2     presses++;
SRAM       presses: 0 -> 1
ISR        interrupt service routine: runs, returns

// Arduino Uno R3: a push button from pin 2 to GND
volatile uint16_t presses = 0;
void onPress() { presses++; }

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), onPress, FALLING);
}

void loop() {
  noInterrupts();
  uint16_t n = presses;
  interrupts();
  Serial.println(n);
  delay(500);
}

The card shows the shared variable, the ISR and loop(). The whole sketch also starts Serial at 9600 baud, sets pin 2 as INPUT_PULLUP, attaches onPress() to its FALLING edge with attachInterrupt(), and waits 500 ms at the end of loop(). Which byte the compiler loads first is its choice; the avr-libc atomic example shows the low byte first, which is what the figure uses. Either order can tear. The torn read only happens when a press lands inside a window a few instructions long, so it is rare: it passes tests and then fails in the field.