Search code examples
stm32stm32f0

Triggering interrupt on GPIO_Pin_4 (GPIOB) on STM32F042


I am looking for a sample code for triggering an interrupt upon signal changes on GPIO_Pin_4 (GPIOB) on STM32F042. I saw some examples for STMF10x and STMF4x, but nothing for STM32F042. I am not using HAL.


Solution

  • There are several things you need to do to make GPIO interrupt happen. The peripherals of interest include:

    1. GPIOx - Obviously
    2. EXTI - Handles GPIO interrupts, sets edges, masks pins ("Set rising edge interrupt to EXTI5" - note we set the pin number, but not the port here)
    3. SYSCFG - Assigns GPIO port to pin interrupt (make EXTI5 a GPIOA5 interrupt and not GPIOB5 interrupt)
    4. NVIC - Enable interrupts

    GPIO and SYSCFG require clock provided to them from RCC, EXTI doesn't have any clock enable bits in RCC as per reference manual, must be always operational then.

    So the sequence of actions seems to be roughly the following:

    1. Enable GPIO port clock, configure the pin (input, pull-up?)
    2. In EXTI, configure edge and pin number (EXTI1 for GPIOx1, EXTI5 for GPIOx5 etc.), unmask the desired pin.
    3. Enable SYSCFG clock, assign GPIO port to the desired EXTIx (note this rules out having interrupts on PA5 and PB5 at the same time)
    4. Configure EXTI interrupt in NVIC.

    The logic of GPIO interrupts looks more or less like this:
    When the desired edge happens on a GPIO pin, EXTI gets a signal from pin 5 (EXTI5 from GPIOA5 and not from GPIOB5 as per SYSCFG), and if that signal is unmasked, it is sent further into NVIC, which in turn triggers an interrupt.

    Note that some EXTIx can share a single NVIC interrupt, so you will have to check within interrupt handler which EXTIx actually triggered it (in the EXTI registers). In case of your MCU, EXTI0 and EXTI1 share one NVIC interrupt, as do EXTI2 and EXTI3, and there is one NVIC interrupt for EXTI4...EXTI15. It's slightly different for every MCU.

    P.S. I chose to give a detailed explanation rather than just write the code, because 1) "please bro write me code" is a meh teaching material and because 2) you probably wanted to see the code to understand how it works, so I skipped an extra step. Most things you need to do here are only 2-5 lines each, so I think you should be able to handle it now.