Lab 03
Beginner
STM32

Button Input — Toggle LED on STM32

Learn GPIO input by reading a button press and toggling an LED

MCU:STM32F103C8T6 (Blue Pill)
Official reference documentation
01

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
02

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
03

Circuit diagram

04

Code

Study the highlighted firmware, then copy it into the matching development environment. Adapt board pins and initialization before compiling.

main.c
#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.

05

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/..."
06

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.

07 · 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.

Up next · Lab 04

Read an ESP32 analog input

Next Lab
Back to all labs