stm32 hal库写串口2

stm32f103 hal库写串口2的时候,发现只可以发送但不能接收

再检查了cubemx配置无误后
发现,并没有打开中断:

因此我采用:在

void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)

这个函数中加入

__HAL_UART_ENABLE_IT(uartHandle, UART_IT_RXNE);                          /* 使能UART接收中断 */
__HAL_UART_ENABLE_IT(uartHandle, UART_IT_IDLE);                          /* 使能UART总线空闲中断 */

这两句。
但我看到在很多代码中,有这种加法,现在main.c文件中加入:

uint8_t aRxBuffer;            //接收中断缓冲
uint8_t Uart1_RxBuff[256];        //接收缓冲
uint8_t Uart1_Rx_Cnt = 0;        //接收缓冲计数
uint8_t    cAlmStr[] = "数据溢出(大于256)\r\n";

HAL_UART_Receive_IT(&huart1, (uint8_t

  • /* USER CODE BEGIN 4 */
    /**
    
    * @brief  Rx Transfer completed callbacks.
      
    * @param  huart pointer to a UART_HandleTypeDef structure that contains
      
     * the configuration information for the specified UART module.
    
      * @retval None
        */
        void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
        {
          /* Prevent unused argument(s) compilation warning */
          UNUSED(huart);
          /* NOTE: This function Should not be modified, when the callback is needed,
             the HAL_UART_TxCpltCallback could be implemented in the user file
           */
    
        if(Uart1_Rx_Cnt >= 255)  //溢出判断
        {
        	Uart1_Rx_Cnt = 0;
        	memset(Uart1_RxBuff,0x00,sizeof(Uart1_RxBuff));
        	HAL_UART_Transmit(&huart1, (uint8_t *)&cAlmStr, sizeof(cAlmStr),0xFFFF);	
        }
        else
        {
        	Uart1_RxBuff[Uart1_Rx_Cnt++] = aRxBuffer;   //接收数据转存
    
        	if((Uart1_RxBuff[Uart1_Rx_Cnt-1] == 0x0A)&&(Uart1_RxBuff[Uart1_Rx_Cnt-2] == 0x0D)) //判断结束位
        	{
        		HAL_UART_Transmit(&huart1, (uint8_t *)&Uart1_RxBuff, Uart1_Rx_Cnt,0xFFFF); //将收到的信息发送出去
        		Uart1_Rx_Cnt = 0;
        		memset(Uart1_RxBuff,0x00,sizeof(Uart1_RxBuff)); //清空数组
        	}
    
        }
    
        HAL_UART_Receive_IT(&huart1, (uint8_t *)&aRxBuffer, 1);   //再开启接收中断
        }
        /* USER CODE END 4 */
    

第二种方法估计也行,但我并没有尝试,仅仅在此作为记录。

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值