Getting started with GPIO

This article explains what is GPIO 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

  • Learn how to setup the pin and GPIO port in STM32CubeMX
  • Modify the code generated by STM32CubeMX and use the HAL functions

2.2 How

  • Configure the GPIO pin in STM32CubeMX 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 STM32CubeMX

  • New project > Access to board selector on main panel or Menu > File > New Project
  • Select NUCLEO-L476RG

File:SelectL476.png

  • 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)

LedPinGPIO.png LED UM GPIO.png

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.

File:GPIO config.png

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

File:GPIO Speed.png

2.3.3 Set the project details for generation

File:Manage GPIO Project.png

2.3.4 Open the main.c in our IDE
  • We do the LED toggling in a function inside main.c
Info white.png Information
Between /* USER CODE BEGIN 3 */ and /* USER CODE END 3 */ tags
 /* 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.
Warning white.png Warning
All GPIOs are able to drive 5 V and 3 V in input mode, but they are only able to generate 3 V in output push-pull mode