目录
CubeMX配置
调试配置
时钟配置
打开串口2的中断
配置串口2波特率等
串口3同理就不展示了
代码
com.h
#ifndef __COM_H__
#define __COM_H__
typedef struct {
char TxBuffer[256];
char RxBuffer[256];
char aRxBuffer;
char Last_aRxBuffer;
char Last_Last_aRxBuffer;
char Rx_Cnt ;
char Rx_Length ;
char flag;
} UART;
extern UART uart2;
extern UART uart3;
void com_init();
void com_send();
void com_receive();
#endif
com.c
#include "com.h"
#include "usart.h"
UART uart2;
UART uart3;
//通信初始化,放在初始化里
void com_init(){
uart2.flag=0;
uart2.Rx_Cnt=0;
uart2.Rx_Length=10;//根据串口通信的数据长度来定
uart3.flag=0;
uart3.Rx_Cnt=0;
uart3.Rx_Length=6;//根据串口通信的数据长度来定
HAL_UART_Receive_IT(&huart2, (uint8_t *)&(uart2.aRxBuffer), 1);
HAL_UART_Receive_IT(&huart3, (uint8_t *)&(uart3.aRxBuffer), 1);
}
//发送,放在代码里循环执行,发送比解码多两位头帧255和254
void com_send(){
TxBuffer[0]=255;
TxBuffer[1]=254;
TxBuffer[2]=(uint8_t)(encoder[0].speed_sum>>8);
TxBuffer[3]=(uint8_t)encoder[0].speed_sum;
TxBuffer[4]=(uint8_t)(encoder[1].speed_sum>>8);
TxBuffer[5]=(uint8_t)encoder[1].speed_sum;
TxBuffer[6]=(uint8_t)(encoder[2].speed_sum>>8);
TxBuffer[7]=(uint8_t)encoder[2].speed_sum;
HAL_UART_Transmit(&huart3, TxBuffer, 8, 10000);
}
//解码,放在代码里循环执行,这里只是演示,具体写法据情况而定
void com_receive(){
encoder[0]=(((short)uart3.RxBuffer[0])<<8)+((short)uart3.RxBuffer[1]);
encoder[1]=(((short)uart3.RxBuffer[2])<<8)+((short)uart3.RxBuffer[3]);
encoder[2]=(((short)uart3.RxBuffer[4])<<8)+((short)uart3.RxBuffer[5]);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
if (huart->Instance == USART2)
{
if(uart2.Last_aRxBuffer==254&&uart2.Last_Last_aRxBuffer==255&&uart2.flag==0)
{
uart2.Rx_Cnt = 0;
uart2.flag=1;
}
if(uart2.flag==1)
{
uart2.RxBuffer[uart2.Rx_Cnt]=uart2.aRxBuffer;
uart2.Rx_Cnt++;
}
if(uart2.Rx_Cnt==uart2.Rx_Length)
{
uart2.flag=0;
}
uart2.Last_Last_aRxBuffer=uart2.Last_aRxBuffer;
uart2.Last_aRxBuffer=uart2.aRxBuffer;
HAL_UART_Receive_IT(&huart2, (uint8_t *)&(uart2.aRxBuffer), 1);
}
if (huart->Instance == USART3)
{
if(uart3.Last_aRxBuffer==254&&uart3.Last_Last_aRxBuffer==255&&uart3.flag==0)
{
uart3.Rx_Cnt = 0;
uart3.flag=1;
}
if(uart3.flag==1)
{
uart3.RxBuffer[uart3.Rx_Cnt]=uart3.aRxBuffer;
uart3.Rx_Cnt++;
}
if(uart3.Rx_Cnt==uart3.Rx_Length)
{
uart3.flag=0;
}
uart3.Last_Last_aRxBuffer=uart3.Last_aRxBuffer;
uart3.Last_aRxBuffer=uart3.aRxBuffer;
HAL_UART_Receive_IT(&huart3, (uint8_t *)&(uart3.aRxBuffer), 1);
}
}
标签:STM32F103,Cnt,aRxBuffer,Rx,Last,uart3,uart2,串口,HAL
From: https://blog.csdn.net/w111155855/article/details/139806077