USART串口
除了IDE自带的debug功能,串口也是程序调试中经常使用的功能。
串口配置
打开引脚图,开启USART功能,这里选择USART1,也就是PA10和PA9。
这里设置串口的参数,异步,波特率115200,数据位8位,无校验,停止位1位,全双工。
自动生成配置代码
使用软件自动生成如下代码。
这里有两个Init,xxx_Init 和 xxx_MspInit
仔细一看,xxx_MspInit中配置的是与硬件相关的,而xxx_Init与硬件无关的配置。
发送数据
HAL_UART_Transmit函数
HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, const uint8_t *pData, uint16_t Size, uint32_t Timeout)
阻塞式发送函数,发送未完成时函数阻塞
重定向printf函数
添加stdio.h的头文件。
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
HAL_UART_Transmit( &huart1 , (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
这样以后调试,就可以使用printf打印调试信息。
接收数据
可以使用main的while循环里,使用HAL_UART_Receive轮询接收,
也可以使用中断模式, 使用HAL_UART_Receive_IT开启,重写HAL_UART_RxCpltCallback回调处理函数。
这里我们使用中断模式接收。,打开串口的全局中断
配置NVIC中断嵌套优先级,这里由于就这个一个中断,随便配一个4。
HAL_UART_Receive_IT
以非阻塞模式接收一定数量的数据。
HAL_UART_RxCpltCallback
重写HAL_UART_RxCpltCallback函数,在收到中断后,会自动调用回调函数。
代码部分
char aRxBuffer[100]; // 接收缓存
//重定向printf
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
HAL_UART_Transmit( &huart1 , (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
int aRxBufferIndex = 0;
// 串口中断回调
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart == &huart1)
{
if(aRxBufferIndex >= 100) {
aRxBufferIndex = 0;
}
aRxBufferIndex ++;
HAL_UART_Receive_IT(&huart1, (uint8_t *)&aRxBuffer[aRxBufferIndex], 1);
}
HAL_UART_Receive_IT(&huart1,(uint8_t *)&aRxBuffer,1); // 启UART中断接受模式
printf("hello World\r\n");