volatile and sharing data with an ISR
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
An interrupt service routine (ISR) and loop() often share a global variable: the ISR counts button presses, loop() reads the count. On an Arduino Uno R3 two things can go wrong. The compiler may keep a stale copy in a CPU register, which volatile prevents. And the 8-bit ATmega328P reads a 16-bit variable one byte at a time, so an interrupt between the two loads can turn 255 into 511; volatile does not prevent that, but turning interrupts off for the copy does. The lesson “Interrupts in firmware: attachInterrupt, edges and latency” sets up the interrupt itself; here we share its data safely.
The ISR changes a variable
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.
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
اقرأ الدرس خطوة بخطوة
The ISR changes a variable
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.
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, returnsloop() reads the same variable
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().
line 5 uint16_t n = presses; SRAM -> register line 7 Serial.println(n); prints 1 writer onPress() (any moment) reader loop() (over and over)Without volatile: a stale copy
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.
line 1 uint16_t presses = 0; (no volatile) compiler "nothing here changes presses": read SRAM once, keep the register copy SRAM presses = 3 register n = 1 (stale)volatile: read memory every time
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.
line 1 volatile uint16_t presses = 0; volatile every read goes to SRAM, every write too line 5 n = presses -> 3 Arduino rule: a variable shared with an ISR is volatile16 bits, one byte per load
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.
CPU 8-bit: one byte per load uint16_t 2 bytes -> 2 loads presses 255 = 0x00 0xFF load 1 low byte (first, as in the avr-libc example) load 2 high byteInterrupted between two loads
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.
load 1 low byte 0xFF ISR presses 255 -> 256 (0x01 0x00) load 2 high byte 0x01 n 0x01 0xFF = 511 torn: neither 255 nor 256 volatile does not stop thisFix: interrupts off for the copy
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.
line 4 noInterrupts(); I bit = 0 press INTF0 = 1, the ISR waits line 5 two loads: 0x00 0xFF -> n = 255 critical section: code that must not be interruptedinterrupts(): the ISR runs late
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.
line 6 interrupts(); I bit = 1 INTF0 was set -> onPress() runs now SRAM presses = 256 line 7 prints 255, next pass prints 256Keep both short
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().
inside noInterrupts() copy only, then interrupts() inside the ISR no delay(), no Serial millis() does not advance there slow work in loop(), on the copy n same thing, tidier ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { n = presses; }
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01What does declaring a variable volatile tell the compiler?
volatile stops the compiler from keeping a copy in a register and skipping reads or writes. It does not make an access atomic.
02Without volatile, the ISR has raised presses to 3 but loop() still prints 1. Why?
Nothing in loop() changes presses, so the optimizer may read it once and keep the register copy. The ISR's updates land in SRAM, which loop() never reads again.
03presses is a volatile uint16_t holding 255 (0x00FF). loop() loads the low byte, then the ISR adds 1, then loop() loads the high byte. What does loop() get?
The low byte was read before the ISR (0xFF) and the high byte after it (0x01): 0x01FF = 511, a value presses never held. This is a torn read, and volatile does not prevent it.
04A press arrives while loop() is between noInterrupts() and interrupts(). What happens to it?
The datasheet says an interrupt that occurs while the global interrupt enable bit is cleared sets its flag, which is remembered until the bit is set again. The press is delayed, not lost.
05Which of these belongs inside an ISR?
An ISR should be short: change the shared variable and return. delay() does not work inside an ISR, Serial data can be lost, and waiting loops hold up every other interrupt.
المسرد
- Interrupt service routine (ISR)
- A function the hardware runs when an interrupt fires, such as onPress() for a button on pin 2. It pauses loop() and returns to it when done.
- Shared variable
- A global variable used by both an ISR and the main program, such as a press counter.
- volatile
- A C/C++ qualifier telling the compiler a variable can change outside the code it sees, so every read and write must really go to memory.
- CPU register
- A tiny storage slot inside the processor. The compiler keeps values there to avoid slower trips to SRAM.
- Atomic
- Done in one piece: nothing can interrupt it halfway. On an 8-bit AVR, reading one byte is atomic but reading two bytes is not.
- Torn read
- A read that mixes bytes from before and after an update, giving a value the variable never held.
- Critical section
- A short piece of code run with interrupts off so it cannot be interrupted, such as copying a multi-byte shared variable.
- Interrupt flag
- A bit the hardware sets when an interrupt event happens (INTF0 for INT0). If interrupts are off, it waits until they are turned back on.
الملاحظات والمصادر
- 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().
- Whether a missing volatile breaks the program depends on the optimizer: the code may work today and fail after a small change or a new compiler version. The avr-libc FAQ shows the classic case, a loop waiting on a flag that never re-reads it.
- 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.
- A single read of a one-byte volatile variable (uint8_t or bool) is one load, so it cannot be torn. A read-modify-write such as count++ in loop(), or reading and then clearing a counter, still needs interrupts off around it.
- ATOMIC_BLOCK(ATOMIC_RESTORESTATE) from <util/atomic.h> does the same as noInterrupts() and interrupts(), but restores the I bit to whatever it was before, on every way out of the block (ATOMIC_FORCEON would always turn interrupts back on).
- A real push button bounces: its contacts can make and break several times in a press, so one press may count more than once. The lesson “Debouncing a button” handles that.
- Arduino language reference: volatile (source)
- Arduino language reference: attachInterrupt() (source)
- Arduino language reference: noInterrupts() (source)
- avr-libc FAQ: a variable updated within an interrupt routine
- avr-libc <util/atomic.h>: atomically and non-atomically executed code blocks
- avr-libc <avr/interrupt.h>: cli(), sei() and the I bit in SREG
- Microchip ATmega328P datasheet (DS40002061B): Reset and Interrupt Handling, EIFR
- cppreference: volatile type qualifier (C)
- J. W. Valvano, Embedded Systems: Shape the World, ch. 12: Interrupts (UT Austin)
اختبار يتاح بعد الخطوة الأخيرة.