Step1、串口初始化函数
void SerialPort_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1, ENABLE);
}
Step2、串口发送函数
void SendArr(uint16_t * Arr, uint16_t Size) {
for (uint16_t i = 0; i < Size; i++) {
USART_SendData(USART1, *(Arr + i));
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
}
void SendStr(char * Str) {
for(uint8_t i = 0; *(Str + i) != '\0'; i++) {
USART_SendData(USART1, *(Str + i));
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
}
Step3、串口接收函数
void USART1_IRQHandler(void) {//以接收包头为0xff包尾为0xee载荷数据4位为例
static uint8_t myindex = 0;
static uint8_t flag = 0;
if (USART_GetITStatus(USART1, USART_IT_RXNE) == SET) {
uint16_t RxData = USART_ReceiveData(USART1);
if(flag == 0 && RxData == Packetheader) {//验证包头
flag = 1;
}
else if(flag == 1) {
RxDataPack[myindex++] = RxData;
while(myindex == Capacity) {
flag = 2;
myindex = 0;
}
}
else if(flag == 2 && RxData == Packettail) {//验证包尾
flag = 0;
RxFlag = RXSET;//置位
}
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
}
Step4、主函数
int main(){
SerialPort_Init();
uint16_t arr[] = {0xff, 0x22, 0x33, 0x88, 0x66, 0xee};
SendArr(arr, sizeof(arr) / sizeof(uint16_t));
// SendStr("hello world\r\n");//验证串口发送接口
while(1){
if(RxFlag == RXSET)//串口接收完毕
SendArr(RxDataPack, sizeof(RxDataPack) / sizeof(uint16_t));
RxFlag = RXRESET;
}
}
Step5、封装
#define Capacity 4//载荷数据数量
#define Packetheader 0xff//自定义包头
#define Packettail 0xee//自定义包尾
typedef enum {
RXSET,
RXRESET
}Rx;
Rx RxFlag = RXRESET;
uint16_t RxDataPack[Capacity];