The working principle of GPIO in STM32

 The GPIO (General Purpose Input/Output) pins on an STM32 microcontroller are highly flexible and are used to interact with external devices—like LEDs, buttons, sensors, or other ICs. Here's a clear explanation of the working principle of GPIO in STM32:




Basic Working Principle of GPIO in STM32

Each GPIO pin can be configured as:

  • Input (read external signal)

  • Output (drive a signal high or low)

  • Alternate function (used by peripherals like USART, SPI, etc.)

  • Analog (e.g., for ADC inputs)


GPIO Workflow in STM32

1. Clock Enable (RCC)

Before using any GPIO port (A, B, C, ...), you must enable its clock in the RCC (Reset and Clock Control):

c

RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; // Enable clock for GPIOA

2. Pin Mode Configuration

Each pin has a mode set in MODER register:

c

GPIOA->MODER &= ~(3 << (2 * 5)); // Clear mode for PA5 GPIOA->MODER |= (1 << (2 * 5)); // Set PA5 as output

Modes:

  • 00: Input

  • 01: Output

  • 10: Alternate Function

  • 11: Analog


3. Output Type

Set output type in OTYPER:

c

GPIOA->OTYPER &= ~(1 << 5); // Push-pull (default)

Types:

  • 0: Push-pull (normal output)

  • 1: Open-drain (needs pull-up resistor)


4. Speed Configuration

In OSPEEDR, select output speed (low, medium, high, very high):

c

GPIOA->OSPEEDR |= (2 << (2 * 5)); // High speed for PA5

5. Pull-up / Pull-down Configuration

Set pull-up/down resistors in PUPDR:

c

GPIOA->PUPDR &= ~(3 << (2 * 5)); // No pull-up/down GPIOA->PUPDR |= (1 << (2 * 5)); // Pull-up for PA5

6. Write to Output Pin

Set/reset pin using ODR or BSRR:

c

GPIOA->ODR |= (1 << 5); // Set PA5 high GPIOA->ODR &= ~(1 << 5); // Set PA5 low // OR atomically: GPIOA->BSRR = (1 << 5); // Set PA5 GPIOA->BSRR = (1 << (5 + 16)); // Reset PA5

7. Read from Input Pin

Read input using the IDR register:

c

uint8_t pin_state = (GPIOA->IDR & (1 << 5)) ? 1 : 0;

 Example: Toggle LED on PA5

c

void init_GPIOA5_output() { RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; // Enable GPIOA GPIOA->MODER &= ~(3 << (2 * 5)); GPIOA->MODER |= (1 << (2 * 5)); // PA5 as output GPIOA->OTYPER &= ~(1 << 5); // Push-pull GPIOA->OSPEEDR |= (2 << (2 * 5)); // High speed GPIOA->PUPDR &= ~(3 << (2 * 5)); // No pull } void toggle_LED() { GPIOA->ODR ^= (1 << 5); // Toggle PA5 }

 Summary Table

FeatureRegister
Mode selectionMODER
Output typeOTYPER
Output speedOSPEEDR
Pull-up/downPUPDR
Read inputIDR
Write outputODR, BSRR

评论

此博客中的热门博文

Detailed Explanation of STM32 HAL Library Clock System

How To Connect Stm32 To PC?

How to add a GPS sensor to ESP32 for Wokwi?