The next example just configure the USART in UART mode with 9600 bauds, 8 bits, no parity 1 bit stop. The program only send a short message every one second in polling mode, what means the HAL_UART_Transmit
will only returns after the message is completely send, or after 5 seconds if the message could not be send
#include "bsp.h"
UART_HandleTypeDef UartHandle; /*uart handler structure*/
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)
{
/*Transmit a string of characters every second with a timeout of 5 seconds.
since Tx is made using polling the last paramter indicates the max time to wait
in case peripheral never sends the data*/
HAL_UART_Transmit( &UartHandle, "Hello\r\n", sizeof("Hello\r\n"), 5000 );
HAL_Delay( 1000 );
}
}
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 );
}