Simvik

Route a pin's interrupt, from the reference manual

Use the SYSCFG and EXTI register descriptions and the vector table to send any pin's edges to its interrupt. A medium embedded C problem (Reading datasheets…

medium · Reading datasheets and schematics · datasheets · registers · interrupts

Write int exti_route(char port, int pin, int rising, int falling), which makes edges on pin pin of port port (a letter, such as 'C') set EXTI line pin's pending bit and raise its interrupt. rising and falling say which edges count; a call for a line already in use replaces its port and edges.

Return the interrupt's position in the vector table, which the caller then enables in the NVIC, or -1 without changing anything if the port does not exist on this chip or the pin is not 0 to 15. Work from the Datasheet excerpt below, and change only the bits of the line you route.

Datasheet excerpt

RCC_APB2ENR (reference manual)

BitFieldDescription
14SYSCFGEN1: the SYSCFG's clock is on. Its registers ignore writes while it is off

SYSCFG_EXTICR1 to SYSCFG_EXTICR4 (reference manual)

EXTI line y is connected to pin y of one port at a time. Line y's 4-bit field EXTIy[3:0] is in SYSCFG_EXTICR(y / 4 + 1), at bits 4 × (y mod 4) + 3 to 4 × (y mod 4).

EXTIy[3:0]Source
0000PA[y]
0001PB[y]
0010PC[y]
0011PD[y]
0100PE[y]
0111PH[y]
othersreserved (this package has no ports F and G)

EXTI registers (reference manual)

OffsetRegisterBit y
0x00IMR1: line y's interrupt is not masked
0x08RTSR1: a rising edge on line y sets its pending bit
0x0CFTSR1: a falling edge on line y sets its pending bit

Vector table (reference manual, excerpt)

PositionAcronymDescription
6EXTI0EXTI line 0 interrupt
7EXTI1EXTI line 1 interrupt
8EXTI2EXTI line 2 interrupt
9EXTI3EXTI line 3 interrupt
10EXTI4EXTI line 4 interrupt
23EXTI9_5EXTI lines 5 to 9 interrupts
40EXTI15_10EXTI lines 10 to 15 interrupts

Starter code

int exti_route(char port, int pin, int rising, int falling) {
  SYSCFG->EXTICR[pin / 4] = (uint32_t)(port - 'A') << ((pin % 4) * 4);
  if (rising) EXTI->RTSR |= 1u << pin;
  if (falling) EXTI->FTSR |= 1u << pin;
  EXTI->IMR |= 1u << pin;
  return 6 + pin;
}

Example tests

The user button on PC13, falling edge

printf("IRQ %d\n", exti_route('C', 13, 0, 1));
show();

Expected output:

IRQ 40
EXTICR 0000 0000 0000 0020 IMR 2000 RTSR 0000 FTSR 2000 APB2ENR 4000

Learn it first

More Reading datasheets and schematics problems