Subsection 9.2.8 Part 7: Changing Data in an ISR, and GPIOx_BSRR
Here are two programs that solve the same problem (reset a counter when the button is pressed) and both of them work. The one on the left is six lines shorter, because it does the reset in the ISR instead of setting a flag for
main() to act on.
volatile int counter;
int main(void) {
uart2_init();
pb4_exti_init();
counter = 0;
while(1) {
counter++;
}
return 0;
}
void EXTI4_15_IRQHandler(void){
if (EXTI->FPR1 & EXTI_FPR1_FPIF4) {
EXTI->FPR1 = EXTI_FPR1_FPIF4;
counter = 0;
}
}
volatile int buttonPushed;
int main(void) {
int counter = 0;
uart2_init();
pb4_exti_init();
buttonPushed = 0;
while(1) {
if (buttonPushed) {
counter = 0;
buttonPushed = 0;
} else {
counter++;
}
}
return 0;
}
void EXTI4_15_IRQHandler(void){
if (EXTI->FPR1 & EXTI_FPR1_FPIF4) {
EXTI->FPR1 = EXTI_FPR1_FPIF4;
buttonPushed = 1;
}
}
The left program resets the counter in the ISR; the right one sets a flag and lets
main() do the reset.
volatile int counter;
int main(void) {
pb4_exti_init();
counter = 0;
while(1) {
counter++;
}
return 0;
}
void EXTI4_15_IRQHandler(void){
if (EXTI->FPR1 & EXTI_FPR1_FPIF4){
EXTI->FPR1 = EXTI_FPR1_FPIF4;
counter = 0;
}
}
volatile int buttonPushed = 0;
int main(void) {
int counter = 0;
pb4_exti_init();
while(1) {
if (buttonPushed) {
counter = 0;
buttonPushed = 0;
} else { counter++; }
}
return 0;
}
void EXTI4_15_IRQHandler(void){
if (EXTI->FPR1 & EXTI_FPR1_FPIF4){
EXTI->FPR1 = EXTI_FPR1_FPIF4;
buttonPushed = 1;
}
}
-
Which of the two would you put in a product, and why?
-
Whichever you chose: what, specifically, would have to go wrong for the other one to be the better choice?
Your answers to both questions:
Activity 9.2.5. Which One Would You Use?
There is no right answer yet. You are about to find out why the obvious one fails. Commit to one before we look.
(a)
Which of the two would you put in a product, and why?
(b)
Whichever you chose: what, specifically, would have to go wrong for the other one to be the better choice?
The difference is not style. In either program
counter++ is one line of C that becomes several machine instructions, and the machine code is where the problem lives. Here is the version with the counter reset in the ISR, the left-hand one:
0800013e: ldr r3, [pc, #12] ; load the ADDRESS of counter into r3
08000140: ldr r3, [r3, #0] ; load the VALUE of counter into r3
08000142: adds r2, r3, #1 ; r2 = r3 + 1 <-- interrupted HERE?
08000144: ldr r3, [pc, #4] ; load the address of counter again
08000146: str r2, [r3, #0] ; store r2 back into counter
The value of
counter is fetched into a register, one is added to the copy, and the copy is written back. An interrupt can land between any two of those instructions. Suppose the button is pressed after the counter value has been fetched: the CPU stacks its state, including that register, runs the ISR, which sets
counter to 0, and returns. The stacked state is restored, and execution resumes at the
adds. The register still holds the old count. One is added to it. It is stored.
The reset is gone, the counter continues from where it was, and there is no error and no warning anywhere.
The right-hand version cannot fail this way. Its ISR writes
buttonPushed, a variable
main() only ever
stores to:
buttonPushed = 0; is a single store, not a read-modify-write, so there is no stale copy left in a register to be written back over the ISRβs update. If the interrupt lands during the
counter++ in the
else branch, no harm is done: the flag is still set when the loop comes round again, and the reset happens one iteration late instead of never.
One small vulnerability does remain: a second press arriving between
if (buttonPushed) and
buttonPushed = 0; sets the flag, and that clearing line then clears the new press along with the first, so the second press is never acted on: the two presses have been
coalesced into one. Here that costs nothing: the counter was reset a moment earlier and would only have been reset again. But notice the difference in kind. The left-hand version
corrupts a count; this one
merges two events into one, and the second failure is both milder and much easier to live with. It is also the shape to look for whenever a consumer clears a flag it did not test and clear in one indivisible step.
SubsectionΒ 9.3.5 says what closes it, and what that costs.
The moral is a distinction worth carrying out of this course. An ISR setting a
control signal, a flag saying βthis happenedβ, cannot corrupt it.
main() writes that flag too, but both sides only ever
store a whole value into it, never read it, change it and write it back, so neither can be caught half-finished by the other; the worst that can happen is that two events merge, as above. An ISR changing
data that the main program also changes is a different thing entirely: when it fails (rarely) it does so silently. Rare and silent is the worst combination a bug can have. Be very careful about modifying shared data in an ISR; often the right answer is not to.
The difference is not style: in either program
counter++ is one line of C that becomes several machine instructions. Here is the version with the
counter reset in the ISR, the left-hand one:
; the LEFT-hand program: main() while(1) { counter++; } the ISR counter = 0;
0800013e: ldr r3, [pc, #12] ; load the ADDRESS of counter into r3
08000140: ldr r3, [r3, #0] ; load the VALUE of counter into r3
08000142: adds r2, r3, #1 ; r2 = r3 + 1 <-- interrupted HERE?
08000144: ldr r3, [pc, #4] ; load the address of counter again
08000146: str r2, [r3, #0] ; store r2 back into counter
-
Suppose the button press lands after the counter value is fetched. The CPU stacks its state, including r3, runs the ISR, which sets counter to 0, and returns.
-
The state is restored and execution resumes at the adds. r3 still holds the old count. One is added to it. It is stored.
-
The reset is gone, the counter carries on from where it was, and there is no error and no warning anywhere.
-
The right-hand program cannot fail this way: main() only ever stores to the flag, so there is no stale copy to write back. Interrupted during counter++, the flag is still set next time round, and the reset happens one iteration late instead of never.
Distinguish between data signals and control signals (flags).
-
An ISR setting a control signal, a flag saying βthis happenedβ, cannot corrupt it. main() writes that flag too, but both sides only ever store a whole value into it, never read it, change it and write it back, so neither can be caught half-finished by the other.
-
An ISR changing data that the main program also changes is a different thing entirely: when it fails (rarely) it does so silently. Rare and silent is the worst combination a bug can have.
-
Be very careful about modifying shared data in an ISR. Often the right answer is not to.
-
Some fine print: the flag pattern does not avoid every issue. If a second press arrives between if (buttonPushed) and buttonPushed = 0;, that clearing line clears the new press along with the first, and the second press is never acted on. The reference section of this chapter explains how to prevent even this.
Now look back at the homework we reviewed at the start of class. That ISR contained
GPIOA->ODR ^= LED;, and it worked. But
^= is a read-modify-write, exactly like
counter++: read
ODR, flip one bit in the copy, write the whole register back. The reason it worked is that nothing else in that program touched
ODR, so there was never anything to lose.
That assumption does not survive the next thing you build. In Lab 5, one of the additional features has a green LED lit while the temperature is below the set point, and a red LED flashing at 1 Hz once it is above: the flashing timed by a timer, the green driven from the main loop, and all three of the labβs LEDs on PA5, PA6 and PA7. One port, one
ODR, two pieces of code writing it. Here is the shape of it, and it is worth reading slowly:
// in main(): // in the timer ISR:
GPIOA->ODR |= GREEN; GPIOA->ODR ^= RED;
Both are read-modify-write on the same register. If the timer interrupt lands after
main() has read
ODR but before it writes back, the ISRβs change to the red LED is present in the register and absent from the copy
main() is holding, and
main()βs write-back overwrites it. The red LED misses a toggle. This would happen only sometimes, and not in a repeatable fashion, which makes this kind of bug very difficult to find.
The fix is in a note at the bottom of the ODR page, the reference manual (
RM0490) Β§6.4.6.
Now look back at the homework we reviewed at the start of class. That ISR contained
GPIOA->ODR ^= LED;, and it worked.
^= is a read-modify-write, exactly like
counter++: read ODR, flip one bit in the copy, write the whole register back. It worked because
nothing else in that program touched ODR.
// in main(): // in the timer ISR:
GPIOA->ODR |= GREEN; GPIOA->ODR ^= RED;
-
This is Lab 5βs Additional Feature 1: a green LED driven from the main loop, a red LED flashed at 1 Hz by a timer, and the labβs three LEDs all on PA5βPA7. One port, one ODR, two pieces of code writing it.
-
If the interrupt lands after main() has read ODR but before it writes back, the ISRβs change to the red LED is in the register and absent from the copy main() is holding, and the write-back overwrites it. The red LED misses a toggle.
-
This bug would happen only sometimes, and not in a repeatable fashion. This makes it very difficult to find this kind of bug.
-
What would you want the hardware to give you here so that you could avoid this issue?
Activity 9.2.6. Find the Fix, Then Write It.
Open RM0490 Β§6.4.6,
GPIO port output data register, the ODR page.
(a)
Read the
Note at the bottom of the ODR description. What does it tell you to use, and for what?
(b)
Follow it to Β§6.4.7. The register has two halves. What does writing a 1 to bit 5 do? What does writing a 1 to bit 21 do? What does writing a 0 to either do?
(c)
Read the access row under the bits. What can you learn by
reading this register?
(d)
The CMSIS names for those two bits are
GPIO_BSRR_BS5 and
GPIO_BSRR_BR5. Write the single line of C that turns PA5 on, and the single line that turns it off.
The note says: βFor atomic bit set/reset, the OD bits can be individually set and/or reset by writing to the GPIOx_BSRR register.β The
bit set/reset register is thirty-two bits covering sixteen pins twice over: writing 1 to
BSy in bits [15:0] sets pin
\(y\)βs output bit, and writing 1 to
BRy in bits [31:16] clears it. Writing 0 anywhere does nothing at all. And both halves are
write-only, a read always returns zero.
GPIOA->BSRR = GPIO_BSRR_BS5; // PA5 high -- one write, no read
GPIOA->BSRR = GPIO_BSRR_BR5; // PA5 low -- one write, no read
That is what the manual calls an
atomic bit set/reset: the pin is set or cleared by a single write, with no read first, so the operation happens whole or not at all and an interrupt cannot land in the middle of it.
ODR |= GREEN has to read the register to preserve the other fifteen pins;
BSRR = GPIO_BSRR_BS5 does not, because the bits it does not mention are bits it does not touch. There is no window between a read and a write-back, because there is no read. One write can now set some pins and clear others and disturb no other pin.
BSRR has no
toggle. There is a set half and a clear half and nothing that inverts, so an ISR that wants to flip a pin still has to know the pinβs current state from somewhere, and BSRR does not directly replace
ODR ^= LED. What it does is make the set and the clear uninterruptible.
What makes a toggle safe is keeping the pinβs state in a variable that only one side ever writes, here the ISRβs
redOn, and driving the pin with BSRR. This is the Lab 5 red LED, written the way that survives a green LED being driven from
main() on the same port:
volatile int redOn = 0; // the ISR owns this; main() never writes it
void TIM14_IRQHandler(void) {
__disable_irq();
TIM14->SR = ~TIM_SR_UIF;
redOn = !redOn; // flip our own copy of the state ...
if (redOn) { GPIOA->BSRR = GPIO_BSRR_BS6; } // ... then one write:
else { GPIOA->BSRR = GPIO_BSRR_BR6; } // set it, or clear it
__enable_irq();
}
Nothing here reads
ODR, so nothing here can lose
main()βs green LED, and nothing in
main() writes
redOn, so nothing there can lose the red one. That is the same distinction arriving a second time, in hardware: the ISR and
main() exchange a control signal rather than sharing data. The remaining small print (what happens if you write a 1 to both
BSy and
BRy, and the
GPIOx_BRR register that duplicates BSRRβs upper half) is in
SubsectionΒ 9.3.4.
RM0490 Β§6.4.6, under ODR, says: βFor atomic bit set/reset, the OD bits can be individually set and/or reset by writing to the GPIOx_BSRR register.β
GPIOA->BSRR = GPIO_BSRR_BS5; // PA5 high -- one write, no read
GPIOA->BSRR = GPIO_BSRR_BR5; // PA5 low -- one write, no read
-
The bit set/reset register is 32 bits covering 16 pins twice: 1 to BSy in bits [15:0] sets pin yβs output bit, 1 to BRy in bits [31:16] clears it. Writing 0 anywhere does nothing at all.
-
Both halves are write-only: a read always returns 0. This is what RM0490 calls an atomic bit set/reset. The pin is set or cleared by a single write, with no read first, so the operation happens whole or not at all and an interrupt cannot land in the middle of it.
-
ODR |= GREEN must read the register to preserve the other fifteen pins. BSRR = GPIO_BSRR_BS5 does not, because the bits it does not mention are bits it does not touch.
-
One write can set some pins and clear others and disturb no other pin.
BSRR has no toggle. There is a set half, a clear half and nothing that inverts, so BSRR does not directly replace
ODR ^= LED. What it does is make the set and the clear uninterruptible. Here is the toggle written using BSRR, on Lab 5βs red LED (PA6):
volatile int redOn = 0; // the ISR owns this; main() never writes it
void TIM14_IRQHandler(void) {
__disable_irq();
TIM14->SR = ~TIM_SR_UIF;
redOn = !redOn; // flip our own copy of the state ...
if (redOn) { GPIOA->BSRR = GPIO_BSRR_BS6; } // ... then one write,
else { GPIOA->BSRR = GPIO_BSRR_BR6; } // set it or clear it
__enable_irq();
}
-
Nothing here reads ODR, so nothing here can lose main()βs green LED. Nothing in main() writes redOn, so nothing there can lose the red one.
-
Keep the pinβs state in a variable that only one side ever writes: here the ISR owns redOn and main() never touches it. Then drive the pin with BSRR. The ISR and main() are exchanging a control signal rather than sharing data, which is the same distinction we drew earlier today, now in hardware.