Interrupt variable exceeds volatile long's 8bit size

To answer the first question, volatile is a modifier that tells the compiler that a variable might be updated externally so it doesn't accidentally optimize it out. It doesn't affect the size of the variable.

The second question is a common concern in shared-data systems. It's possible that while the main loop is in the middle of accessing a multi-byte variable, an interrupt occurs and changes that variable, leading to corrupted data. There are many ways of handling this situation (and in fact, asking about this is one of my favorite interview questions). On an arduino the easiest way is probably to disable interrupts before accessing the shared data and re-enable it later. e.g.,

volatile unsigned long interruptedVar = 0;
.....

void loop()
{
  noInterrupts();
  interruptedVar = x+5;
  interrupts();
}

void ISR()
{
  interruptedVar++;
}

This temporarily disables interrupts so that loop() can access the variable safely.
HTH.

1 Like