STM32F103 USART Receive (using Keil and STMCubeMX)




In this tutorial, I will demonstrate how to Receive data using USART2 of STM32F103 Nucleo board.

This tutorial is divided into 3 Steps:

  1. Creating Project using STM32CubeMX
  2. Programming in Keil
  3. Visualizing the Output

Step 1: Creating Project Using STM32CubeMX

Open STM32CubeMX. Click on ‘New Project’. From Series Select ‘STMF1’, from ‘lines’ select STM32F103. From MCUs list, select ‘STM32F103RBTx’. Click “OK”.

{See figure:[1]}

Under the Set “Mode” to “Asynchronous” under ‘USART2’ under the ‘Peripherals’ tab. And set ‘PA5’ to ‘GPIO_ouput’.

{See figure:[2]}

Now, click ‘Generate Code’ [Ctrl + Shift + G]. Enter Project name, where to save project and ‘MDK-ARM V5’ under ‘Toolchain / IDE’. Click ‘OK’. Open Generated Code in Keil.

Step 2: Programming in KEIL

Once Project is Open in Keil, Open ‘main.c’ located under ‘Application/User’ Folder, located under ‘ ’ under ‘Project: ’. Scroll down to find ‘#include "stm32f1xx_hal.h". Just After this add following line of code:

#include “string.h”

{See Figure: [3]}

Now, Scroll down into while loop and enter following lines of code:

char buff2[ 6 ] = "\r\n>>>";

HAL_UART_Transmit ( &huart2, buff2, strlen( buff2 ), 10 );

char buff[ 50 ];

memset( buff, 0, 50 );

HAL_UART_Receive( &huart2, buff, 50, 5000 );

if( strcmp( buff, "on" ) == 0 )


HAL_GPIO_WritePin( GPIOA, GPIO_PIN_5, 1 );

} else if( strcmp( buff, "off" ) == 0 )


HAL_GPIO_WritePin( GPIOA, GPIO_PIN_5, 0 );


And thus you Keil window will look like:

{See Figure: [4]}

Click on ‘Build’ Button (or Press ‘F7’). The Connect your STM32 Board and Click on ‘LOAD’ button (or Press ‘F8’)

Step 3: Visualizing the Output

Now, Press the ‘Black’ Rest button on you ‘STM32’ Board.

Now, when we will send “on” to the COM port to which STM32 is connected it will turn LED on our STM board “ON” and when we will send “off”, it will turn LED “OFF”. To send these strings, open Docklight. Open COM port to which you STM32 Board is connected at a Baud Rate of 115200. Click on Start communication button. Now, you should start receiving the following after every 5 seconds:


Like shown in figure below:

{ See figure: [5] }

Now, click on console window on button so that you can type in a window. Now, when a ‘>>>’ appears on next line, you have to type “on” or “off” within next 5 seconds. Now, type in “on” and you will see that as soon as next ‘>>>’ appears LED will be turned “ON”. Now, type in “off” and you will see that as soon as next ‘>>>’ appears LED will be turned “OFF”.

{ See figure: [6] }



    • Arduino Contest 2019

      Arduino Contest 2019
    • Tape Contest

      Tape Contest
    • Trash to Treasure

      Trash to Treasure



    Question 11 months ago on Step 3

    Hello, is it possible to do this example with receive and transmit interrupt?