2
votes

Will an AVR MCU (Arduino) remember all interrupts that happen while in nointerrupts() section?

void f1() {
  noInterrupts();
  // critical, time-sensitive code here
  interrupts();
}
//now jump to queued interrupts if any

Will it execute them after interrupts()?

I ask this because after reading the datasheet, I have the feeling that all interrupts have their flag, so this could be no problem. But I'm not that experienced, and I'm missing something probably, because other tutorials always state vaguely that "don't stay there too long, since no interrupts at all may happen at that time".

Why?

I have a circular buffer where I put some packets from I2C (they are put whenever I2C interrupt occurs). I also read this buffer from the main loop once in a while, at unpredictable time and overwrite is allowed.

Also, I use the same buffer class (but different instances) in the opposite direction (I2C then triggers interrupt and reads).

My problem is: I would like to turn off interrupts during non-interrupt read/write, so I can be sure I will not be in a situation when I2C triggers and overwrites my item being currently read from normal, main loop.

I now kind of handle the situation with flags before and after read, so the interrupt first checks if the item is free, but I'm not confident in that approach, and I would like to make it work with noInterrupts() and interrupts() during main loop read.

Thank you.

1

1 Answers

7
votes

Your approach seems normal. You need to disable interrupts to protect the buffer.

While the interrupts are disabled, interrupt flags will continue to be set but the handlers won't be called. When interrupts are enabled, the interrupt handlers will run.

The warning to not take too long with interrupts disabled is that two of the same type of interrupt may be triggered while disabled. If that happens, the single interrupt flag is set once, and there is no way to tell that there were two interrupts pending. The interrupt handler only runs once. Essentially, the first of the interrupts is lost.