One variable, two writers
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.
loop() copies presses into n, a CPU register, and prints it: 1. Two pieces of code now share one variable. The ISR writes it, loop() reads it, and the ISR can run between any two instructions of loop().
volatile
Delete volatile from line 1. The compiler sees nothing in loop() change presses, so it may load it into a register once and reuse that copy. The ISR counts up to 3 in SRAM; the screen still says 1.
volatile tells the compiler that something it cannot see may change this variable. So every read loads it from SRAM and every write stores it there, never skipped. loop() now prints 3.
Reading it whole
The ATmega328P is an 8-bit CPU: one load moves one byte. presses is a uint16_t, two bytes, so line 5 takes two loads. Say presses has reached 255: high byte 0x00, low byte 0xFF.
Without lines 4 and 6: loop() loads the low byte, 0xFF. Then a press runs the ISR, making presses 256: 0x01 0x00. loop() loads the high byte, 0x01. n is 511, a value presses never held.
noInterrupts() clears the I bit, the switch that lets interrupts in. A press now only sets the INT0 flag, which waits. loop() loads both bytes, 0x00 0xFF: n is 255, whole.
interrupts() sets the I bit again. The waiting flag runs onPress() at once and presses becomes 256. loop() prints 255; on its next pass it copies 256. No press is lost, only delayed by a few instructions.
While interrupts are off, every interrupt waits, including the timer behind millis(). So copy and get out: no Serial or delay() between lines 4 and 6. Keep the ISR short too: change the variable, return, and do slow work in loop().
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.