# Easily Use scanf on STM32

**URL:** <https://forum.digikey.com/t/easily-use-scanf-on-stm32/21103>\
**Category:** Development Boards, Kits, Programmers\
**Tags:** stmicroelectronics, evaluation-boards, tech-tips\
**Created:** [March 24, 2022, 2:18pm UTC](https://forum.digikey.com/t/easily-use-scanf-on-stm32/21103 "2022-03-24T14:18:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Matt\_Mielke](https://sea2.discourse-cdn.com/digikey/user_avatar/forum.digikey.com/matt_mielke/32/71373_2.png) [@Matt\_Mielke](https://forum.digikey.com/u/Matt_Mielke)\
**Post date:** [March 24, 2022, 2:18pm UTC](https://forum.digikey.com/t/easily-use-scanf-on-stm32/21103/1 "2022-03-24T14:18:32Z")

</div>

While there are many approaches to interfacing with embedded systems, one of the simplest and most versatile is with user input from a serial console. Rather than manually parse the incoming ASCII characters and convert them to the appropriate data format, the `scanf()` function is often used to do so automatically. However, like the `printf()` function, some additional code must be supplied to utilize this `stdio` library function. Intended as a companion to [Easily Use printf on STM32](https://forum.digikey.com/t/easily-use-printf-on-stm32/20157), this article goes a step further by also mapping the UART peripheral to the `scanf()` function.

# Procedure

The following steps can be directly applied to any [STM32CubeIDE](https://www.st.com/en/development-tools/stm32cubeide.html) project (version 1.9.0 at the time of writing). If another development environment is preferred, this procedure may have to be modified slightly to accommodate any differences.

## 0. Establish a UART Instance

As a preliminary step, ensure that a UART (or USART) peripheral has been properly configured for sending and receiving data to a virtual COM port. On [ST development boards](https://www.digikey.com/en/product-highlight/s/stmicroelectronics/stm32-kits), this likely means choosing the UART RX and TX lines connected to the ST-LINK programmer/debugger. See the corresponding step in [Easily Use printf on STM32](https://forum.digikey.com/t/easily-use-printf-on-stm32/20157) for complete details.

## 1. Redirect scanf() to UART Instance

a. In the Private Includes section of the `main.c` file, add an include directive for the `stdio` library, as shown in Figure 1.

 ![Include the stdio library](https://global.discourse-cdn.com/digikey/original/3X/5/5/55480d3c010218770c7be7aa365249b1591996e1.png)  
**Figure 1:** Including the `stdio` library

b. To redirect the `scanf()` function only, copy and paste the code provided in Listing 1 into the Private Function Prototypes section of `main.c`. To redirect both the `scanf()` and `prinf()` functions (as most applications will require) copy the code provided in Listing 2 instead.

**Listing 1:** Simple code for redirecting `scanf()`

```cpp
#ifdef __GNUC__
#define GETCHAR_PROTOTYPE int __io_getchar(void)
#else
#define GETCHAR_PROTOTYPE int fgetc(FILE *f)
#endif

GETCHAR_PROTOTYPE
{
  uint8_t ch = 0;

  /* Clear the Overrun flag just before receiving the first character */
  __HAL_UART_CLEAR_OREFLAG(&huart?);

  /* Wait for reception of a character on the USART RX line and echo this
   * character on console */
  HAL_UART_Receive(&huart?, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
  HAL_UART_Transmit(&huart?, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
  return ch;
}

```

**Listing 2:** Simple code for redirecting both `printf()` and `scanf()`

```cpp
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#define GETCHAR_PROTOTYPE int __io_getchar(void)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#define GETCHAR_PROTOTYPE int fgetc(FILE *f)
#endif

PUTCHAR_PROTOTYPE
{
  HAL_UART_Transmit(&huart?, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
  return ch;
}

GETCHAR_PROTOTYPE
{
  uint8_t ch = 0;

  /* Clear the Overrun flag just before receiving the first character */
  __HAL_UART_CLEAR_OREFLAG(&huart?);

  /* Wait for reception of a character on the USART RX line and echo this
   * character on console */
  HAL_UART_Receive(&huart?, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
  HAL_UART_Transmit(&huart?, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
  return ch;
}

```

**Be sure to change the dummy UART handles used in the Listings above to that of your desired UART peripheral.** For example, Figure 2 shows `huart2` being utilized as the target UART instance.

 ![code added to private function prototypes](https://global.discourse-cdn.com/digikey/original/3X/6/2/62f7c2249c8dd92628c203c1670bdc2237cdf6e2.png)  
**Figure 2:** Adding retargeting code to `main.c` file

c. Unfortunately, the default `syscalls.c` file automatically generated by STM32CubeIDE results in unexpected behavior when internal buffering of the input stream is enabled. The simplest solution to this issue is to disable buffering _before_ any call to `scanf()` is made. Copy and paste the line of code provided in Listing 3 into the initialization section of the `main()` function.

**Listing 3:** Disable internal buffering for the input stream

```cpp
setvbuf(stdin, NULL, _IONBF, 0);

```

The `scanf()` function should now function properly for all but the floating point format specifiers. To enable those, continue on to the next step.

## 2. Enable Floating Point Support (Optional)

Similar to the `printf()` function, floating point support must be explicitly enabled for `scanf()` if the application demands that floating point numbers be read from the serial input. Otherwise, any call to `scanf()` with floating point specifiers in the format string will behave unexpectedly.

a. Right-click on the project name in the Project Explorer and choose **Properties**. Select **Settings** in the “C/C++ Build” category and choose **MCU Settings** under the _Tool Settings_ tab. Check the box next to “Use float with scanf from newlib-nano” as shown in Figure 3 below. Click **Apply and Close**.

 ![use float with scanf](https://global.discourse-cdn.com/digikey/original/3X/e/7/e70978233e8a216dffe29a088ea76e8cdd9b253c.png)  
**Figure 3:** Enabling float formatting support

# Results

Using the example code from the [`scanf()` reference page](https://www.cplusplus.com/reference/cstdio/scanf/) (see Listing 4), we see in Figure 4 that the user input is properly read and formatted.

**Listing 4:** Example code for testing

```cpp
char str[80];
int i;

printf("Enter your family name: ");
scanf("%79s", str);
printf("Enter your age: ");
scanf("%d", &i);
printf("Mr. %s, %d years old.\n", str, i);
printf("Enter a hexadecimal number: ");
scanf("%x", &i);
printf("You have entered %#x (%d).\n", i, i);

```

![example code output](https://global.discourse-cdn.com/digikey/original/3X/7/3/739dacfd8ab98440b661c04dfec64b1a3e37cee9.png)  
**Figure 4:** Example code output
