中断方式实现串口通信(基于百问网DshanMCU-F103)

Uart.c代码段

static volatile int g_tx_cplt = 0;

static volatile int g_rx_cplt = 0;

static uint8_t g_RecvChar;

static uint8_t g_RecvBuf[100];

static circle_buf g_uart1_rx_bufs;

发送数据回调函数:

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)

{

       g_tx_cplt = 1;

}

发送成功等待函数

void Wait_Tx_Complete(void)

{

       while(g_tx_cplt == 0);

       g_tx_cplt = 0;

}

接收数据回调函数

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)

{

       g_rx_cplt = 1;

       /*将数据写入环形缓冲区中*/

       circle_buf_write(&g_uart1_rx_bufs,g_RecvChar);

       /*重新使能 RXNE 中断

       不能修改中断函数,在回调函数中添加响应的操作代码

       */

       HAL_UART_Receive_IT(&huart1,&g_RecvChar,1);

}

成功接收等待函数

void Wait_Rx_Complete(void)

{

       while(g_rx_cplt == 0);

       g_rx_cplt = 0;

      

}

启动串口接收函数

void StartUART1Recv(void)

{

       //初始化环形缓冲区

       circle_buf_init(&g_uart1_rx_bufs,100,g_RecvBuf);

       //使能RXNE中断

       HAL_UART_Receive_IT(&huart1,&g_RecvChar,1);

}

串口获取字符函数

int UART1GetChar(uint8_t *pVal)

{

       return circle_buf_read(&g_uart1_rx_bufs,pVal);

}

主函数Main.c 主要代码

static uint8_t g_data_buf[100];

static circle_buf g_key_bufs;

/*函数声明*/

void Wait_Tx_Complete(void);

void Wait_Rx_Complete(void);

void StartUART1Recv(void);

int UART1GetChar(uint8_t *pVal);

HAL_UART_Transmit(&huart1,str,strlen(str),1000);

      

   //调用HAL_UART_Receive_IT使能RXNE中断

   StartUART1Recv();

     

  while (1)

  {

         HAL_UART_Transmit_IT(&huart1,str2,strlen(str2));

        

         //wait for TC

         Wait_Tx_Complete();

      

         while (UART1GetChar(&c) != 0);

        

         c=c+1;

         HAL_UART_Transmit(&huart1, &c, 1, 1000);

         HAL_UART_Transmit(&huart1, "\r\n", 2, 1000);

中断实现串口通信

发送函数:

HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)

接收函数:

HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)

一般在回调函数中产生中断,实现串口通信的功能:

向PC发送完成回调函数:

HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart);

从接收端向PC发送完成回调函数:

HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)

优点:解决轮询模式中堵塞CPU资源的问题,能够合理利用CPU资源,节省CPU的时间;

弊端:无法实现非定长的数据传输

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值