This article explains what GPIO is and how to use it through examples
1. GPIO definition
GPIO stands for general purpose input/output. It is a type of pin found on an integrated circuit that does not have a specific function. While most pins have a dedicated purpose, such as sending a signal to a certain component, the function of a GPIO pin is customizable and can be controlled by the software.
2. Configure GPIO for LED toggling
2.1. Objective
- In this project, you will learn how to Toggle a pin on STM32L476 Nucleo board using Hardware Abstraction Layer (HAL) library
- Learn how to setup the pin and GPIO port in STM32CubeIDE
2.2. How
- Configure the GPIO pin in STM32CubeIDE and generate the code
- Add into the project the HAL_Delay function and HAL_GPIO_Toggle function
- Verify the correct functionality on toggling LED
2.3. Create the project in STM32CubeIDE
File > New > STM32 Project in main panel.
File:GPIO2.png
- Select NUCLEO-L476RG in board Selector.
- You will then get a popup asking if you want to initialize peripherals to their default configuration
- No need to configure any peripheral as only the core/Flash/SRAMs are used (default peripherals)
- If you want to start the project with a board, the LED pin is already selected (PA5 on NucleoL476RG. For other boards refer to the user manual)
Note: During the download of a firmware package with STM32CubeMX, existing examples can be find at the following path for example:
c:\Users\YourUserName\STM32Cube\Repository\STM32Cube_FW_G0_V1.3.0\Projects\NUCLEO-G071RB\Examples\GPIO\GPIO_IOToggle\GPIO_IOToggle.ioc
and open them with STM32CubeMX.
2.3.1. GPIO configuration
- Select the push-pull mode
- No pull-up and pull-down
- Output speed set to very high is important for faster peripherals such as SPI or USART.
2.3.2. GPIO (pin) output-speed configuration
- Change the rising and falling edge when the pin state changes from high to low or low to high.
- A higher GPIO speed increases the EMI noise from STM32 and increases the STM32 consumption.
- It is good to adapt the GPIO speed with the peripheral speed. For example toggling GPIO on 1 Hz is low optimal settings, but with SPI on 45 MHz the very high must be set..
2.3.3. Set the project details for generation
2.3.4. Open the main.c in our IDE
- We do the LED toggling in a function inside main.c
/* USER CODE BEGIN 3 */
/* Infinite loop */
while (1)
{
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14, GPIO_PIN_SET);
HAL_Delay(500);
HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14, GPIO_PIN_RESET);
HAL_Delay(500);
}
/* USER CODE END 3 */
2.4. Compile and flash
- Every 500 ms the green LED state changes.