一、串口实现printf
1.hal配置
2.重定向代码
#include "stdio.h"
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1,(uint8_t*)&ch,1,5,0xffff);
return 0;
}
int fgetc(FILE *f)
{
uint8_t ch;
HAL_UART_Receive(&huart1,(uint8_t*)&ch,1,5,0xffff);
return ch;
}
二、串口2中断收发
配置同上
1.l轮循环方式发送
uint8_t uart3_txbuf[] = "UART3 Test\r\n";
HAL_UART_Transmit(&huart3, uart3_txbuf,sizeof(uart3_txbuf),100);
2.中断接收
初始化后先执行一次
HAL_UART_Receive_IT(&huart3, uart3_rxbuf, 1);
相关变量
#define MAX_RECV_LENGTH 100
uint8_t uart2_rxbuf[MAX_RECV_LENGTH];
uint16_t uart2_cnt = 0;
uint8_t uart3_rxbuf[MAX_RECV_LENGTH];
uint16_t uart3_cnt = 0;
添加回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance==USART2)
{
if(uart2_cnt<MAX_RECV_LENGTH){
uart2_cnt++;
HAL_UART_Receive_IT(&huart2,uart2_rxbuf+uart2_cnt,1);
}
}
else if(huart->Instance==USART3)
{
if(uart3_cnt<MAX_RECV_LENGTH){
uart3_cnt++;
HAL_UART_Receive_IT(&huart3,uart3_rxbuf+uart3_cnt,1);
}
}
}
|