# Using GPIO on STM32

## 0. Pin Map

On the STM32F446RET6 Nucleo board, the LD2 LED is connected to PA5, and the USER Button is connected to PC13.

> Note: the LED is active high.

We will demonstrate how to set up a generic GPIO output pin with the LED, and a generic GPIO input pin with the user button.

## 1. Configure STM32

First, set the configuration from the [Starter Project](https://tk233.gitbook.io/notes/stm32/getting-started-stm32-edition/going-through-a-starter-project).

Click on **PA5**, set it to "GPIO\_Output".

![](https://1287130752-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvVJ0h2a4qMIhB1I8GdV8%2Fuploads%2Fgit-blob-0e3c3f9ebf52b0bec8feddc9cc94817312059cd6%2Fimage.png?alt=media)

Click on **PC13**, set it to "GPIO\_Input".

![](https://1287130752-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvVJ0h2a4qMIhB1I8GdV8%2Fuploads%2Fgit-blob-46f02ee126dec3e391f1a33226871a012831f034%2Fimage.png?alt=media)

Save the .ioc file and generate code.

## 2. Code

First, add the code from the [Starter Project](https://tk233.gitbook.io/notes/stm32/getting-started-stm32-edition/going-through-a-starter-project).

In `main.c`, add the following code

```c
  /* USER CODE BEGIN 2 */
  char str[64];
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
    HAL_Delay(250);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);
    HAL_Delay(250);

    uint8_t val = HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13);
    sprintf(str, "button value: %d\r\n", val);
    HAL_UART_Transmit(&huart2, (uint8_t *)str, strlen(str), 100);
  }
  /* USER CODE END 3 */
```

![](https://1287130752-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvVJ0h2a4qMIhB1I8GdV8%2Fuploads%2Fgit-blob-de6bf5455a659b1234dab6c2015d7d0c5f9afc9b%2Fimage.png?alt=media)

After saving, upload the code

## 3. Result

We can see LED LD2 blinking, and when we press/release the USER Button, the serial output changes.

![](https://1287130752-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvVJ0h2a4qMIhB1I8GdV8%2Fuploads%2Fgit-blob-cb662c3a41c64573a93d55e52c1cf0938aecd6cd%2Fimage.png?alt=media)
