ENع
→volatile and ISRs
الدرس 14 · Interrupts, timers and PWM

volatile and sharing data with an ISR

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة9 خطوات5 أسئلةIntermediate
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 14 · تفاعلي
01 / 09

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. loop() 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)
  3. 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)
  4. 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 volatile
  5. 16 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 byte
  6. Interrupted 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 this
  7. Fix: 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 interrupted
  8. interrupts(): 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 256
  9. Keep 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; }

اختبار يتاح بعد الخطوة الأخيرة.