Skip to content

Arduino Shared Variable Corruption in Interrupts

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about Arduino Shared Variable Corruption in Interrupts. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Variables shared between ISR and main loop are corrupted or give inconsistent values.

Quick Fix

Wrong

int counter = 0;  // Missing volatile!
Compiler optimizes away the read — counter never updates in loop().
volatile int counter = 0;

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

void loop() {
  int localCounter;
  noInterrupts();  // Disable interrupts for atomic read
  localCounter = counter;
  interrupts();
  Serial.println(localCounter);
  delay(100);
}

void myISR() {
  counter++;
}
Counter value reads consistently (no corruption).

Prevention

Always declare shared variables as volatile. Use noInterrupts()/interrupts() for atomic access to multi-byte variables. For simple reads of 1-byte variables on AVR, interrupts()/noInterrupts() may be optional but is still good practice. On 32-bit boards, use atomic operations or mutexes.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### Why does volatile matter?

volatile tells the compiler that the variable can change outside normal program flow (ISR). Without it, the compiler may optimize reads to a cached register value.

Can I use std::atomic on Arduino?

AVR gcc does not fully support std::atomic. Use noInterrupts()/interrupts() instead. On ESP32, use portMUX or atomicCompareSwap().

Is int access atomic on AVR?

No. int is 2 bytes on AVR. The ISR could fire between reading the high byte and low byte, corrupting the value. Use noInterrupts() around multi-byte reads.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro