STM32 HAL库开发(三)- 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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值