The following example shows how to receive a message of a given number of characters using the serial port in polling mode. Polling mode means the program should read and wait until, for instance four bytes arrive trough the serial port. In this example we wait up to 10 seconds, function HAL_UART_Receive will return after the period of time or if the four bytes arrive.

#include "bsp.h"
#include <string.h>

uint8_t RxBuffer[ 10 ]; /*buffer for message received*/
UART_HandleTypeDef UartHandle; /*declaramos estructura tipo uart*/

int main(void)
{
    HAL_Init(); /*init cube library*/
    
    /*uart configuration options for module USART2, 9600 baudrate,
    8bits, 1 stop bit, no parity, no flow control, and 8 bit lenght */
    UartHandle.Instance         = USART2;
    UartHandle.Init.BaudRate    = 9600;
    UartHandle.Init.WordLength  = UART_WORDLENGTH_8B;
    UartHandle.Init.StopBits    = UART_STOPBITS_1;
    UartHandle.Init.Parity      = UART_PARITY_NONE;
    UartHandle.Init.HwFlowCtl   = UART_HWCONTROL_NONE;
    UartHandle.Init.Mode        = UART_MODE_TX_RX;
    UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;
    /*init uart2 with previous paramters*/
    HAL_UART_Init( &UartHandle );

    while (1)
    {
        /*We wait for 10 seconds if four charatcer arraive through the serial port,
        the message can arraive before the timeout period*/
        if( HAL_UART_Receive( &UartHandle, &RxBuffer[0], 4, 10000 ) == HAL_OK )
        { 
            /*compare the four bytes received against the string "led\r"*/
            if( memcmp( "led\r", RxBuffer, sizeof("led\r")-1 ) == 0 )
            { 
                /* in case the led string has been received do something, like
                for instance toggle a led */
            }
        }
        else
        {
            /*If during the 10 seocnds we didn't receive anything, let s send back
            a "Timeout mesage"*/
            HAL_UART_Transmit( &UartHandle,"Timeout\r\n", 9, 500 );
        }
    }
}

msps.c

/*The function is called from HAL_UART_Init at the very beginning
and allows us to set the pins to be used as serial port*/
void HAL_UART_MspInit( UART_HandleTypeDef *huart )
{
    GPIO_InitTypeDef GPIO_InitStruct; /*gpios init structure*/
    
    __HAL_RCC_USART2_CLK_ENABLE();    /*enable usart2 clock*/
    __HAL_RCC_GPIOA_CLK_ENABLE();     /*eneable port A clock */
    
    /*set pin 2(tx) and pin 3(rx) from port A in altern mode usart2
    the altern mode info can be found in device datasheet*/
    GPIO_InitStruct.Pin   = GPIO_PIN_2 | GPIO_PIN_3;
    GPIO_InitStruct.Mode  = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull  = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF1_USART2;
    /*apply configuration configuracion*/
    HAL_GPIO_Init( GPIOA, &GPIO_InitStruct );
}