Subsection 9.2.7 Part 6: Writing counterResetButtonInt.c
-
A pinโs interrupt goes through the EXTI first, because the STM32C031C6โs 45 GPIO pins will not fit one NVIC line each.
-
Four steps: which port is on the line (EXTICR), which edge counts (FTSR1), whether the line is unmasked (IMR1), and the NVIC. Miss any one and there is no error, no warning, and no interrupt.
-
Twelve lines share EXTI4_15_IRQHandler, so the handler reads FPR1 to learn which line fired, and clears it by writing 1, because the access type says rc_w1.
-
An ISR changing data that main() also changes can lose an update silently. An ISR setting a flag cannot corrupt one, though two presses can still merge into one.
-
GPIOx->BSRR sets or clears a pin with a single write and no read, so there is no window for an interrupt to land in. It has no toggle.
We are now ready to assemble the entire program.
counterResetButtonInt.c contains three blocks of work: TODO 1 is the four EXTI/NVIC steps, in
pb4_exti_init(); TODO 2 is the handler; TODO 3 is the shared flag. Its loop is
counterResetButtonPolled.cโs with the button handling moved out: the delay stays, the printing stays, and the pin is never read in
main() again.
/*
* counterResetButtonInt.c -- reset a counter from a PB4 falling-edge interrupt
*
* Three blocks of work to fill in. We have gone through everything you need:
*
* TODO 1 the four EXTI/NVIC steps port, edge, mask, NVIC
* TODO 2 the handler itself exact name from Table 40
* TODO 3 the shared flag one keyword matters
*/
#include <stdio.h>
#include "ES28.h"
#include "uart.h"
#define MAXCOUNT 100
void pb4_exti_init(void);
// TODO 3a -- declare the flag the ISR shares with main.
int main(void) {
int counter = 0;
uart2_init();
printf("Hex \tDecimal\r\n");
pb4_exti_init();
// TODO 3b -- initialize the flag ...
while(1) {
printf("%x\t%d\r\n", counter, counter);
delay_ms(1000);
// TODO 3c -- fill in the test: when the flag is set, reset the counter
// and clear the flag. One chain, so a press does not reset
// and then immediately increment.
// GPIOB->IDR appears NOWHERE in this loop.
if ( /* TODO 3c */ ) {
} else if (counter == MAXCOUNT) {
counter = 0;
} else {
counter++;
}
}
return 0;
}
void pb4_exti_init(void) {
__disable_irq(); // given: no interrupts during setup
RCC->IOPENR |= RCC_IOPENR_GPIOBEN; // given: the pin configuration you already have
GPIOB->MODER = (GPIOB->MODER & ~GPIO_MODER_MODE4_Msk)
| (GPIO_INPUT << GPIO_MODER_MODE4_Pos);
GPIOB->PUPDR = (GPIOB->PUPDR & ~GPIO_PUPDR_PUPD4_Msk)
| (GPIO_PULLUP << GPIO_PUPDR_PUPD4_Pos);
// TODO 1a -- select port B on line EXTI4. Two lines: clear the field,
// then set it. Mind the array index.
// TODO 1b -- falling edge on line EXTI4
// TODO 1c -- unmask line EXTI4
// TODO 1d -- enable the line in the NVIC
__enable_irq(); // given: setup done, interrupts on
}
// TODO 2 -- write the ISR. Its name comes from Table 40's acronym for the row
// covering lines 4 to 15; copy it from the startup file rather than
// typing it. No arguments, no return value. Inside, bracketed by
// __disable_irq(); ... __enable_irq(); do three things: check that
// the event was on line 4, clear that pending bit, set your flag.
counterResetButtonInt.c contains three blocks of work:
TODO 1 is the four EXTI/NVIC steps, in
pb4_exti_init();
TODO 2 is the handler;
TODO 3 is the shared flag (below).
// TODO 3a -- declare the flag the ISR shares with main.
int main(void) {
int counter = 0;
uart2_init();
pb4_exti_init();
// TODO 3b -- initialize the flag
while(1) {
printf("%x\t%d\r\n", counter, counter);
delay_ms(1000);
// TODO 3c -- when the flag is set, reset the counter and clear the
// flag. One chain, so a press does not reset and then
// immediately increment.
if ( /* TODO 3c */ ) {
} else if (counter == MAXCOUNT) { counter = 0; } else { counter++; }
}
return 0;
}
void pb4_exti_init(void) {
__disable_irq(); // given
// given: pin configuration
// TODO 1a -- select port B on line
// EXTI4. Clear the field,
// then set it. Mind the
// array index.
// TODO 1b -- falling edge on EXTI4
// TODO 1c -- unmask line EXTI4
// TODO 1d -- enable the line in the
// NVIC
__enable_irq(); // given
}
// TODO 2 -- write the ISR. Its name
// comes from Table 40's acronym for
// the row covering lines 4 to 15;
// copy it from the startup file.
// No arguments, no return value.
// Inside, bracketed by
// __disable_irq(); ... __enable_irq();
// do three things: check that the
// event was on line 4, clear that
// pending bit, set your flag.
Activity 9.2.4. Give the Counter a Button It Cannot Miss.
The skeleton is
counterResetButtonInt.c, and you already put it in your
Src folder earlier today.
(a)
Swap the build: exclude
counterResetButtonPolled.c (
Resource Configurations โ Exclude from Build,
Select All, OK) and make sure
counterResetButtonInt.c is
not excluded. Two
main()s cannot coexist in one build.
(b)
Before you build, think about the four steps inside
pb4_exti_init(): selecting the port on the line, choosing the falling edge, unmasking the line, and enabling it in the NVIC. If any one of them is missing, the program still compiles and links with no warnings, and the button never interrupts. Which of the four do you think would take you longest to find, and what would you see on the terminal?
(c)
Fill TODO 1: the four steps, in order (port, edge, mask, NVIC).
(d)
Fill TODO 2: the handler, with its name copied from the startup file.
(e)
Fill TODO 3: the flag, declared, initialized, and used in the loop.
(f)
Build, flash, and give the button the same short tap that the polled version missed. Try tapping it several times during a single one-second interval.
(g)
Done early? Add the Nucleoโs blue user button, on PC13, so that pressing it reverses the counting direction. PC13 is also on lines 4 to 15, so it shares your handler, which means the handler now has to tell the two apart. You will need a second initialization function, and a second field in a different
EXTICR register. This is also part of tonightโs homework.
Counter not resetting? Walk these in order; each rules out a layer.
-
Does the
polled version still work? Swap the build back for a moment. If it does, the wiring is fine and the fault is somewhere in the interrupt path. If it does not, the fault is the button or the capacitor: re-seat both against
Figureย 2.4.5 and run the polled version again. No amount of reading your EXTI code will find a loose wire.
-
Is the port selection in EXTI->EXTICR[1], index one, and is the value EXTI_PB shifted into the EXTI4 field? A port code left at 0 selects port A, which is a pin you are not pressing.
-
Is the handler named exactly EXTI4_15_IRQHandler, copied from startup_stm32c031c6tx.s? A near-miss name builds and links without a single warning, and your function simply never runs.
-
Are all four steps present: EXTICR, FTSR1, IMR1, and NVIC_EnableIRQ()? Missing any one is silence, and missing the mask is the quietest of them.
One thing you may see again that was hidden with our polling method is contact bounce. Recall that a mechanical switch does not make one clean transition; its contacts bounce, which we captured on the oscilloscope earlier (
Subsectionย 2.1.3). Polling could not double-count a press: it read the pin once a second, and a single reading of a level either says pressed or it does not. It cannot count edges at all, so bouncing contacts were invisible to it. An edge-triggered interrupt
does count edges: it fires on every falling edge it sees, and a bouncing contact can deliver several. The debouncing capacitor is what keeps that from happening here. If your counter ever jumps by more than one pressโs worth, look at the capacitor before you look at the code: you may need a larger capacitor, to increase the RC (resistor-capacitor) time constant.
The link below opens the same exercise in the simulator, for working on it away from your Nucleo. Click
+ Button in the component bay, the parts list to the right of the board, then click the Arduino header pin labeled
D5, which is PB4, and hold it down to press it. That one click closes the same pushbutton you wired to PB4: one side to the pin, the other to GND, with the pull-up inside the chip holding the pin HIGH until the button connects it. The debouncing capacitor across the switch (
Figureย 2.4.5) is not modeled, so nothing here bounces.
All four switches are in the register panel,
EXTI->EXTICR[1],
EXTI->FTSR1,
EXTI->IMR1 and
NVIC->ISER, beside
EXTI->FPR1, as soon as your program touches the EXTI.
EXTI->IMR1 resets to 0xFFF8 0000, so look at bit 4 rather than at the whole word. When a press sets
FPR1โs bit and the counter still does not reset, the EXTI half of the chain is working and the fault is past it: the NVIC line, or the handlerโs name.
Run
counterResetButtonPolled.c from the examples list first. A short tap sometimes resets the counter and sometimes does not, and a press-and-hold always does, for the same reason as on your board: the loop reads the pin once a second and spends the rest of the time inside
delay_ms(). Then run your own version and tap it the same way.
Two words of caution. This simulator does not optimize your code, so a flag shared between the interrupt handler and
main() works here whether or not its declaration carries
volatile. TODO 3 asks which keyword that declaration must carry, and a counter that resets in the simulator is not evidence that you have it right. And an interrupt here is taken between two C statements, never part way through one, so the half-finished read-modify-write of
Subsectionย 9.2.8 cannot happen in the simulator: that one has to be reasoned about rather than tried.
The simulator does not save your code, so use the download button (the downward arrow) to keep a copy of your work.
Open in the board simulator (new tab)
Add the Nucleoโs blue user button. It is on
PC13, and pressing it should reverse the counting direction. This is also part of tonightโs homework.
-
PC13 is on lines 4 to 15 as well, so it shares EXTI4_15_IRQHandler with PB4: the handler now has to tell the two apart.
-
You will need a second initialization function, and a second field in a different EXTICR register: work out which one.
-
The blue button is wired on the Nucleo already, so there is nothing to add on the breadboard. It is pulled up there too, so like PB4 it idles HIGH and a press is a falling edge.
Counter not resetting? Check the below steps in order: each one rules out a layer.
-
1: Does the polled version still work? Swap the build back for a moment. If it does, the wiring is fine and the fault is in the interrupt path. If it does not the fault is the button or the capacitor, and no amount of reading your EXTI code will find it: check and fix your wiring.
-
2: Is the port selection in EXTI->EXTICR[1], and is the value EXTI_PB shifted into the EXTI4 field? A port code left at 0 selects port A, a pin you are not pressing.
-
3: Is the handler named exactly EXTI4_15_IRQHandler, copied from the startup file? A near-miss builds and links with zero warnings, and your function simply never runs.
-
4: Are all four steps present: EXTICR, FTSR1, IMR1, NVIC_EnableIRQ()?
One thing you may see again that was hidden with our polling method is contact bounce.
-
Recall that a mechanical switchโs contacts bounce. We captured this on the scope earlier in the course.
-
Polling could not double-count a press: it read the pin once a second, and a single reading of a level either says pressed or it does not. It cannot count edges at all, so bouncing contacts were invisible to it. An edge-triggered interrupt does count edges: it fires on every falling edge, and a bouncing contact can deliver several.
-
The debouncing capacitor is what keeps that from happening here. If your counter ever jumps by more than one pressโs worth, look at the capacitor before you look at the code: you may need a larger capacitor, to increase the RC (resistor-capacitor) time constant.