工具:
单片机:STM32L053R8T6(NUCLEO板)
STM32cube
简介:STM32与上位机之间用通信协议(自己定义)进行串口通信。怎么判断上位机发过来的指令是正确的,而不是一串乱码?怎么从正确的指令中提取出想要的命令代号,从而实现想要的功能?
方法:读取上位机发来的命令,逐位判断命令的包头和包尾,如果能对应上,则这串指令是正确的,然后从指令中提取想要的数据和命令等。举个栗子:通信协议是自己定义的,不是modbus协议等。。如F0 5A 15 15 25 16 09 02 12 14 FF A5 F0(都是16进制),F0 5A是包头,A5 F0是包尾,黑色15是命令代号,中间蓝色是我想发的数据,橙色FF是校验位。只要包头包尾校验正确,基本这串指令不会有问题。
UART中断函数:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
{
unsigned char temp;
receive0[receive0_tail]=aRxBuffer;
temp=receive0[receive0_tail];
if((temp == 0xf0)&&(head0_flag == 0))
{
head0_flag=1;
receive0_len=1;
}
else if(head0_flag == 1)
{
if(temp==0x5a)
{
head0_flag = 2;
receive0_len++;
}
else
{
head0_flag = 0;
}
}
else if ((temp==0xa5)&&(head0_flag == 2))
{
head0_flag = 3;
receive0_len++;
}
else if (head0_flag == 3)
{
receive0_len++;
if(temp==0xf0)
{
head0_flag = 0;
HW0_COM=1;
}
else
{
head0_flag = 2;
}
}
else
{
receive0_len++;
if(receive0_len>70)
{
receive0_len=0;
head0_flag = 0;
}
}
receive0_tail++;
if(receive0_tail>=128)
{
receive0_tail=0;
}
HAL_UART_Receive_IT(&huart1,&aRxBuffer,1);
}
main函数:其中main函数是测试程序,把串口助手发来的数据再上传回去,目的是看发送和读取是否一致。
int main(void)
{
uint8_t txbuf[100];
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
command=0;
receive0_tail=0;
receive0_len=0;
HW0_COM=0;
/* USER CODE END 2 */
memcpy(txbuf,"这是一个串口中断接收回显实验\n",100);
HAL_UART_Transmit(&huart1,txbuf,strlen((char *)txbuf),1000);
HAL_UART_Receive_IT(&huart1,&aRxBuffer,1);
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
command=ReadComm();
switch(command)
{
case 0x15:
{
// memcpy(txbuf,"这是0x15\n",100);
// HAL_UART_Transmit(&huart1,txbuf,strlen((char *)txbuf),1000);
HAL_UART_Transmit(&huart1,receive0,strlen((char *)receive0),1000);
HW0_COM=0;
receive0_len=0;
head0_flag = 0;
receive0_tail=0;
break;
}
case 0x1a:
{
// memcpy(txbuf,"这是0x1a\n",100);
// HAL_UART_Transmit(&huart1,txbuf,strlen((char *)txbuf),1000);
HAL_UART_Transmit(&huart1,receive0,strlen((char *)receive0),1000);
HW0_COM=0;
receive0_len=0;
head0_flag = 0;
receive0_tail=0;
break;
}
default:
break;
}
command=0;
}
/* USER CODE END 3 */
}