To configure GPIO pins on STM32, you typically use either STM32CubeMX/STM32CubeIDE (GUI-based) or directly manipulate registers or HAL/LL APIs (code-based). Here's how to do it step-by-step:
Method 1: Using STM32CubeMX or STM32CubeIDE (Graphical Interface)
Steps:
1. Create a New Project
- Open STM32CubeIDE or STM32CubeMX.
- Select your MCU or board (e.g., STM32F103C8T6, Nucleo-F446RE).
2. Configure the GPIO Pins
- Click on the pin in the Pinout View.
- Assign its function: GPIO_Input, GPIO_Output, Alternate Function, etc.
-
In the Configuration Pane, you can set:
- Mode: Input / Output / Alternate Function / Analog
- Output Type: Push-Pull or Open-Drain
- Pull-up / Pull-down: None, Pull-up, or Pull-down
- Speed: Low / Medium / High / Very High
3. Configure System Clock (if needed)
4. Generate Code
- Click “Project > Generate Code”.
- CubeMX will generate initialization code using the HAL drivers.
5. Write Application Code
In main.c, use HAL functions like HAL_GPIO_WritePin() or HAL_GPIO_ReadPin() to control or read from the pin.
Method 2: Using HAL Code Manually
Example for configuring PA5 as Output using HAL:
c
GPIO_InitTypeDef GPIO_InitStruct = {0};
__HAL_RCC_GPIOA_CLK_ENABLE(); // Enable GPIOA clock
GPIO_InitStruct.Pin = GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; // Push-pull output
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// Toggle PA5
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
Method 3: Using Low-Level (LL) Drivers
LL drivers are lighter and faster:
c
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA);
LL_GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = LL_GPIO_PIN_5;
GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT;
GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL;
GPIO_InitStruct.Pull = LL_GPIO_PULL_NO;
LL_GPIO_Init(GPIOA, &GPIO_InitStruct);
// Set or reset
LL_GPIO_SetOutputPin(GPIOA, LL_GPIO_PIN_5);
LL_GPIO_ResetOutputPin(GPIOA, LL_GPIO_PIN_5);
Common GPIO Modes:
Summary
Top comments (0)