1.CUBEMAX配置
![](https://i-blog.csdnimg.cn/blog_migrate/fd15c7aada55df0886bb42aaa89d3ece.png)
2.题目要求实现
3.代码模板实现
char rxdata[30];
char txdata[30];
uint8_t rxdat;
uint8_t rx_count;
uint8_t rx_timer;
bool rx_finish_flag;
uint8_t password[3]={1,2,3};
void setup()
{
HAL_TIM_Base_Start_IT(&htim4);
HAL_UART_Receive_IT(&huart1, &rxdat, 1);
}
void loop()
{
usart_proc();
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART1)
{
rx_timer=0;
rx_finish_flag=0;
rxdata[rx_count++]=rxdat;
HAL_UART_Receive_IT(&huart1,&rxdat,1);
}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM4)
{
if(rx_finish_flag==0)rx_timer++;
}
}
void usart_proc()
{
if(rx_count>0)
{
if(rx_timer>=3)
{
rx_timer=0;
if(rxdata[rx_count-1]==rxdat)rx_finish_flag=1;
}
if(rx_finish_flag==1)
{
rx_finish_flag=0;
if(rx_count==7)
{
if(rxdata[3]=='-'&&rxdata[4]>='0'&&rxdata[4]<='9'&&rxdata[5]>='0'&&rxdata[5]
<='9'&&rxdata[6]>='0'&&rxdata[6]<='9'&&rxdata[0]-'0'==password[0]&&rxdata[1]-
'0'==password[1]&&rxdata[2]-'0'==password[2])
{
password[0]=rxdata[4]-'0';
password[1]=rxdata[5]-'0';
password[2]=rxdata[6]-'0';
sprintf(txdata,"Successfully\r\n");
HAL_UART_Transmit(&huart1,(uint8_t *)txdata,sizeof(txdata),50);
}
else{
sprintf(txdata,"Errror\r\n");
HAL_UART_Transmit(&huart1,(uint8_t *)txdata,sizeof(txdata),50);
}
}
else{
sprintf(txdata,"Errror\r\n");
HAL_UART_Transmit(&huart1,(uint8_t *)txdata,sizeof(txdata),50);
}
rx_count=0;//这一段放在 if(rx_finish_flag==1)里面
memset(rxdata,0,sizeof(rxdata));
}
}
}
#ifndef __fun_h
#define __fun_h
#include "stm32G4xx.h"
#include "head.h"
void setup(void);
void loop(void);
void usart_proc(void);
#endif
4.代码模板实现二
void usart_proc()
{
if(rx_count==7)
{
if(rxdata[3]=='-'&&rxdata[4]>='0'&&rxdata[4]<='9'&&rxdata[5]>='0'&&rxdata[5]<='9'&&rxdata[6]>='0'&&rxdata[6]<='9'&&rxdata[0]-'0'==password[0]&&rxdata[1]-'0'==password[1]&&rxdata[2]-'0'==password[2])
{
password[0]=rxdata[4]-'0';
password[1]=rxdata[5]-'0';
password[2]=rxdata[6]-'0';
sprintf(txdata,"Successfully\r\n");
HAL_UART_Transmit(&huart1,(uint8_t *)txdata,sizeof(txdata),50);
}
else{
sprintf(txdata,"Errror\r\n");
HAL_UART_Transmit(&huart1,(uint8_t *)txdata,sizeof(txdata),50);
}
}
else{
sprintf(txdata,"Errror\r\n");
HAL_UART_Transmit(&huart1,(uint8_t *)txdata,sizeof(txdata),50);
}
rx_count=0;
memset(rxdata,0,sizeof(rxdata));
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART1)
{
rxdata[rx_count++]=rxdat;
HAL_UART_Receive_IT(&huart1,&rxdat,1);
}
}
void loop()
{
if(rx_count!=0)
{
int temp=rx_count;
HAL_Delay(1);
if(temp==rx_count) usart_proc();
}
}