GPIO input: read the button
In input mode the code reads the voltage on a pin. We set the button pin PC13 as an input with a pull-up resistor, and turn the LED on while the button is held.
In this lesson · 4 steps
Input mode
The chip compares the pin voltage with a threshold: below it reads 0, above it reads 1. With a button, pressing it pulls the pin to ground, so it reads 0. When you let go, the voltage goes back up and it reads 1.
Pull-up and pull-down resistors
When the button is not pressed, a pin with only a button on it is connected to nothing. It is floating, and it can read 0 or 1 at random.
A pull-up resistor connects the pin to 3.3 V, so it reads 1 by default and 0 when the button pulls it to ground. A pull-down resistor does the opposite. STM32 pins have both built in: you turn one on in CubeMX, no extra part needed.
1PC13 as an input, named BUTTON
- We stay in
STM32_GPIO_PROGRAMMING. In CubeIDE's Project Explorer, double-clickSTM32_GPIO_PROGRAMMING.ioc: it opens in CubeMX (lesson 0.2 links the two; or use File → Load Project in CubeMX) - Click PC13 →
GPIO_Input, then right-click → Enter User Label →BUTTON
2Turn on the pull-up
- In the Pinout & Configuration tab, in the Categories list on the left: System Core → GPIO → select PC13 → GPIO Pull-up/Pull-down =
Pull-up - Generate Code. Your blink code is kept: it is inside a USER CODE section
- Back in CubeIDE, right-click the project → Refresh (F5), so it shows the new code
3Read the button in the loop
If the pin reads RESET (0), the button is pressed: LED on. Otherwise LED off.Grey lines are already in the file: add only the coloured ones. Copy takes just those.
/* USER CODE BEGIN WHILE */ while (1) { if (HAL_GPIO_ReadPin(BUTTON_GPIO_Port, BUTTON_Pin) == GPIO_PIN_RESET) { /* button pressed: with the pull-up, the pin reads RESET when pressed */ HAL_GPIO_WritePin(LED_CONTROL_GPIO_Port, LED_CONTROL_Pin, GPIO_PIN_SET); } else { HAL_GPIO_WritePin(LED_CONTROL_GPIO_Port, LED_CONTROL_Pin, GPIO_PIN_RESET); } /* USER CODE END WHILE */
HAL_GPIO_ReadPin returns GPIO_PIN_SET (1) or GPIO_PIN_RESET (0). Because of the pull-up, pressed means RESET.4Build and run
- Terminate the last debug session if it still runs, then Debug and Resume
Check & troubleshoot
What you should see
- Hold the blue button (B1): the green LED is on
- Let go: the LED is off
If it doesn't work
- LED is on when the button is not pressed: the comparison is the wrong way round; pressed is
GPIO_PIN_RESET - Build error on BUTTON_Pin: the label on PC13 must be exactly
BUTTON - Nothing happens: check PC13 is set to
GPIO_Inputand generate the code again
Good to know
- The loop checks the button thousands of times per second, even when nothing changes. Chapter 2 fixes that with an interrupt.