Button Input — Toggle LED on STM32
Learn GPIO input by reading a button press and toggling an LED
What you'll learn
- Configuring GPIO as input
- Reading digital input with HAL_GPIO_ReadPin()
- Debouncing a button in software
- Toggling output based on input state
Components needed
- STM32F103C8T6 Blue PillPA0 button input and PC13 LED output
- Push buttonNormally open momentary button
- 10k ohm resistor (pull-up)Holds PA0 high while the button is released
- LED + 220 ohm resistorExternal indicator, or use the onboard PC13 LED
- Breadboard and jumper wiresFor the button and external LED circuit
Circuit diagram
Circuit diagram placeholder
Connect 3.3 V → 10 kΩ pull-up → PA0, and PA0 → push button → GND. PC13 controls the typical active-low onboard LED; an external LED requires a 220 Ω series resistor.
Diagram coming soonCode
Study the highlighted firmware, then copy it into the matching development environment. Adapt board pins and initialization before compiling.
#include "main.h"
#define BUTTON_PIN GPIO_PIN_0#define BUTTON_PORT GPIOA#define LED_PIN GPIO_PIN_13#define LED_PORT GPIOC
void SystemClock_Config(void);static void MX_GPIO_Init(void);
int main(void){ HAL_Init(); SystemClock_Config(); MX_GPIO_Init();
uint8_t lastState = GPIO_PIN_SET;
while (1) { uint8_t currentState = HAL_GPIO_ReadPin(BUTTON_PORT, BUTTON_PIN);
if (lastState == GPIO_PIN_SET && currentState == GPIO_PIN_RESET) { HAL_GPIO_TogglePin(LED_PORT, LED_PIN); HAL_Delay(50); // debounce }
lastState = currentState; HAL_Delay(10); }}The pull-up keeps PA0 high until the button connects it to ground. The code detects that high-to-low transition, toggles PC13 and waits 50 ms to reduce contact-bounce effects. STM32CubeIDE generates the GPIO and clock initialization.
Simulate It
Run the circuit in your browser when a Wokwi simulation is connected to this lesson.
Wokwi simulation placeholder
Add the public Wokwi embed URL for this lab to launch the interactive simulator here.
wokwiEmbedUrl: "https://wokwi.com/projects/..."Expected Output
PA0 reads high while the button is released and low while pressed. Each new press toggles the LED; holding the button does not repeatedly toggle it.
Expected output image placeholder
Expected STM32 button input and toggled LED output placeholder
Diagram coming soon07 · Challenge Task
Take this lab further
Change the debounce delay and compare the results. Then modify the code so the LED toggles on button release instead of button press.