Learn / Pins: in and out · guide 3 of 10

Read the user button

Pressing the blue user button B1 toggles the green LED LD7, first by polling the pin and then from an interrupt, and you know why a press must be debounced.

Beginner≈ 40 minBefore this:Blink an LEDTopics:GPIO

Reading a button is the first time the outside world talks to your program. You find out how B1 is wired, read its pin in a loop, then let the hardware call you with an external interrupt instead. Finally you deal with the mechanical bounce that makes one press look like several.

You will learn
  • Read a wiring diagram to learn whether a button is high or low when pressed
  • Configure a pin as an input and read it with GPIOx_IDR
  • How a pin edge becomes an interrupt: EXTI line, SYSCFG_EXTICRx, the NVIC and the handler
  • Why you must clear the pending bit, and why a button needs debouncing
You need
  • STM32H750B-DK and a USB cable to CN14 (the ST-LINK connector)
  • STM32CubeIDE installed

On this board

Pulled from the datasheet tables and the board schematic. Click a pin for everything the finder knows about it.

PinBallBoard netUsed here asAFOpen
PC13E3WAKEUPB1, blue user button (HIGH while pressed)
PJ2T6LED1LD7, green user LED (active-low), our feedback
1

Find the button and follow its wire

The user manual says the blue button B1 is "available to be used as a digital input or as Wakeup alternate function". It does not name the pin. The schematic does: B1 ends on net WAKEUP, which is PC13. The black button B2 is wired to the reset of the MCU, so you cannot read it from code.

Now follow the wiring on the MCU sheet: 3V3 → B1 → R230 (330 Ω) → PC13, and a second resistor R229 (220 kΩ) from the same net to GND. With the button open, the 220 kΩ resistor holds the pin at 0 V. When you press it, 3.3 V reaches the pin through R230 and the pin reads 1. So this button is high when pressed, the opposite of the active-low LEDs.

R229 is an external pull-down, so you do not need to switch on an internal one.

Tip. The same schematic area has a capacitor footprint C182 marked DNF (do not fit): the capacitor that would filter the button in hardware is not on the board, so the bouncing in step 5 is yours to handle in software.

2

Turn on the port clock and make PC13 an input

The recipe is the same as for the LED, with an input instead of an output. First the clock: GPIO port C is bit GPIOCEN in RCC_AHB4ENR. Then the mode: GPIOx_MODER has two bits per pin, and the reset value for port C is all ones, so PC13 starts as 11 (analog). An input is 00, so you must clear both bits.

Leave GPIOx_PUPDR at 00 (no internal pull), because of the resistor on the board.

3

Read it in a loop (polling)

The simplest way to use a button is to ask the pin over and over. GPIOx_IDR holds the current level of all 16 pins of the port as bits: bit 13 is PC13. The loop below copies the button to the LED: pressed means drive PJ2 low, because LD7 is active-low.

This is called polling. It works, but the CPU does nothing else while it waits, and if your program is busy for 100 ms (say it is drawing on the screen) it will miss a short press. The next step fixes that.

#include "stm32h7xx.h"   /* with STM32H750xx defined by the project */

int main(void)
{
    /* clocks: port C (button) and port J (LED) */
    RCC->AHB4ENR |= RCC_AHB4ENR_GPIOCEN | RCC_AHB4ENR_GPIOJEN;
    (void)RCC->AHB4ENR;                       /* read back: lets the enable take effect */

    /* PC13 input: MODER13 = 00 (reset value is 11, so clear both bits) */
    GPIOC->MODER &= ~GPIO_MODER_MODE13_Msk;
    GPIOC->PUPDR &= ~GPIO_PUPDR_PUPD13_Msk;   /* no internal pull: the board has R229 */

    /* PJ2 output for LD7: MODER2 = 01, LED off to start (active-low) */
    GPIOJ->MODER = (GPIOJ->MODER & ~GPIO_MODER_MODE2_Msk)
                 | (1U << GPIO_MODER_MODE2_Pos);
    GPIOJ->BSRR = GPIO_BSRR_BS2;

    for (;;) {
        if (GPIOC->IDR & GPIO_IDR_ID13) {
            GPIOJ->BSRR = GPIO_BSRR_BR2;      /* pressed (PC13 high) -> PJ2 low -> LD7 on */
        } else {
            GPIOJ->BSRR = GPIO_BSRR_BS2;      /* released -> LD7 off */
        }
    }
}
4

Let the hardware call you: an external interrupt

An interrupt makes the CPU drop what it is doing, run a small handler function and then continue. For a GPIO pin the signal travels through four stages, and each one has to be set up:

  1. Pin to EXTI line. The EXTI block has 16 GPIO lines, and line n listens to pin n of one port. Which port is picked by SYSCFG_EXTICR4 (it handles lines 12 to 15). The field for line 13 is EXTI13; the value for port C is 0010. SYSCFG is a peripheral too, so its clock SYSCFGEN is in RCC_APB4ENR.
  2. Which edge. EXTI_RTSR1 enables the rising edge for line 13, EXTI_FTSR1 the falling edge. B1 is high when pressed, so a rising edge means "just pressed".
  3. Unmask the line. EXTI_CPUIMR1 bit 13 lets the line interrupt the CPU. In the CMSIS header this register is called EXTI->IMR1.
  4. Enable it in the NVIC. Lines 10 to 15 share one interrupt, EXTI15_10_IRQn. It must be enabled in the NVIC too, or the CPU never hears it.

In the handler you have to clear the pending bit (EXTI_CPUPR1, bit 13) by writing a 1 to it. If you forget, the interrupt is still pending when the handler returns and it runs again at once, forever. The handler's name is fixed by the startup file: EXTI15_10_IRQHandler. Because it serves six lines, check which one fired.

#include "stm32h7xx.h"   /* with STM32H750xx defined by the project */

void EXTI15_10_IRQHandler(void)               /* name comes from the startup file */
{
    if (EXTI->PR1 & EXTI_PR1_PR13) {          /* lines 10..15 share this handler */
        EXTI->PR1 = EXTI_PR1_PR13;            /* write 1 = clear the pending bit */

        /* toggle LD7 (read the output level, then set or reset with BSRR) */
        if (GPIOJ->ODR & GPIO_ODR_OD2) GPIOJ->BSRR = GPIO_BSRR_BR2;
        else                           GPIOJ->BSRR = GPIO_BSRR_BS2;
    }
}

int main(void)
{
    RCC->AHB4ENR |= RCC_AHB4ENR_GPIOCEN | RCC_AHB4ENR_GPIOJEN;
    RCC->APB4ENR |= RCC_APB4ENR_SYSCFGEN;     /* SYSCFG holds EXTICRx */
    (void)RCC->APB4ENR;

    GPIOC->MODER &= ~GPIO_MODER_MODE13_Msk;   /* PC13 input */
    GPIOJ->MODER = (GPIOJ->MODER & ~GPIO_MODER_MODE2_Msk)
                 | (1U << GPIO_MODER_MODE2_Pos);
    GPIOJ->BSRR = GPIO_BSRR_BS2;              /* LD7 off */

    /* 1. EXTI line 13 listens to port C (EXTICR4 is array index 3) */
    SYSCFG->EXTICR[3] = (SYSCFG->EXTICR[3] & ~SYSCFG_EXTICR4_EXTI13_Msk)
                      | SYSCFG_EXTICR4_EXTI13_PC;
    /* 2. rising edge = button pressed */
    EXTI->RTSR1 |= EXTI_RTSR1_TR13;
    /* 3. unmask line 13 for the CPU (this is EXTI_CPUIMR1) */
    EXTI->IMR1  |= EXTI_IMR1_IM13;
    /* 4. enable the shared interrupt in the NVIC */
    NVIC_SetPriority(EXTI15_10_IRQn, 5);
    NVIC_EnableIRQ(EXTI15_10_IRQn);

    for (;;) {
        __WFI();                              /* sleep until an interrupt arrives */
    }
}

Tip. In CubeIDE you can also set the pin to GPIO_EXTI13 in the .ioc file and enable "EXTI line[15:10] interrupts" in the NVIC tab: the generator then writes the same calls for you. What you read above is what ends up happening underneath.

5

Debounce it

Run the interrupt version and press the button a few times. Sometimes the LED seems to ignore a press: it toggled twice. A metal contact does not close cleanly. For a short time (usually a few milliseconds; it varies by button) it bounces between touching and not touching, and each bounce is a real rising edge that the EXTI faithfully reports. Making the program ignore these extra edges is debouncing.

The simplest software fix is a time window: remember when you last accepted a press, and ignore any edge that arrives within the next 30 to 50 ms. You need a millisecond clock for that. Cortex-M's SysTick timer is made for it: configure it for a 1 ms interrupt and count the interrupts. The PWM guide explains SysTick properly; here it is only a counter.

Do not call a delay function inside the handler. A handler should be short: while it runs, interrupts of the same or lower priority have to wait. And HAL_Delay itself needs the SysTick interrupt, so calling it from a handler of higher priority can hang the program.

/* Add to the program from step 4 (bare-metal: no HAL, so no HAL SysTick handler). */
static volatile uint32_t ms;                  /* milliseconds since start */

void SysTick_Handler(void)                    /* runs every 1 ms */
{
    ms++;
}

void EXTI15_10_IRQHandler(void)
{
    static uint32_t last;                     /* time of the last accepted press */

    if (EXTI->PR1 & EXTI_PR1_PR13) {
        EXTI->PR1 = EXTI_PR1_PR13;

        if ((uint32_t)(ms - last) >= 50U) {   /* ignore edges within 50 ms */
            last = ms;
            if (GPIOJ->ODR & GPIO_ODR_OD2) GPIOJ->BSRR = GPIO_BSRR_BR2;
            else                           GPIOJ->BSRR = GPIO_BSRR_BS2;
        }
    }
}

/* in main(), before the loop: 1 ms tick from the core clock.
   SystemCoreClock is 64 MHz after reset (HSI); if you set up the PLL it must hold
   the new frequency (SystemCoreClockUpdate()). */
SysTick_Config(SystemCoreClock / 1000U);

Tip. Subtracting as unsigned numbers (ms - last) keeps the test correct even when the counter wraps around after about 49 days.

6

Build, flash, and make it yours

Put the code in main.c, press Run in STM32CubeIDE, and press the blue button. Then try:

  • Count presses in a variable, and show the count by blinking LD6 (PI13, port I clock) that many times.
  • Trigger on both edges (set EXTI_FTSR1 too, or use GPIO_MODE_IT_RISING_FALLING) so the LED follows the button, and see how the debounce window must change.
  • Hold the button for more than one second to switch between two blink patterns: compare ms at the press and at the release.

Common mistakes

  • Treating the button as active-low. B1 is high when pressed (pull-down, 3.3 V through the switch), the opposite of the LEDs.
  • Forgetting SYSCFGEN. Without the SYSCFG clock your writes to SYSCFG_EXTICR4 are lost and line 13 stays on port A (reset value 0000).
  • Forgetting NVIC_EnableIRQ. The EXTI flags a pending request but the CPU never runs the handler.
  • Not clearing the pending bit in the handler: the interrupt fires again immediately and the program seems to hang in it.
  • Calling a blocking delay inside the handler to "debounce". It stalls other interrupts, and HAL_Delay can hang if SysTick cannot interrupt the handler.
  • Port mix-up: only one pin number n of one port can use EXTI line n. PC13 and PA13 both want line 13.

Check yourself

Try to answer before opening. If you get stuck, the pages linked above have the answer.

Why do we not enable an internal pull resistor on PC13?

The board already has R229 (220 kΩ) as a pull-down to GND, so the pin has a defined level when the button is open. An internal pull-up would fight it and make the "released" level uncertain.

What happens if the handler returns without writing 1 to bit 13 of EXTI_CPUPR1?

The pending bit stays set, the NVIC sees an interrupt that is still pending and calls the handler again straight away, in an endless loop. The bit is cleared by writing a 1 to it.

You want the same button code on PA13 instead of PC13. What changes, and what must you check first?

EXTI13 in SYSCFG_EXTICR4 becomes 0000 (port A) instead of 0010, and the clock bit becomes GPIOAEN. First check what else PA13 does: the datasheet and schematic show it is the debug SWDIO pin, so repurposing it breaks debugging.

Reading list

Every page this guide sent you to, by document. Reading them in order is a good revision.

UM2488UM2488 STM32H745I/H750B-DK Discovery kit user manualp.8p.16
MB1381MB1381 Discovery board schematic (H750XB variant)sheet 3sheet 3
RM0433RM0433 reference manual (STM32H742/743/753/750)p.457p.470p.536p.540p.541p.542p.542p.543p.554p.750p.770p.772p.772p.782p.783
PM0253PM0253 Cortex-M7 programming manualp.41p.184p.212

Search next

Each of these opens the finder with pins, registers, schematic hits and document pages for the term.

Where to go next