串口多命令控制优化
注意
简单方法
接收到串口信息后,使用Switch case 语法进行case判断,根据串口接收到的数据进行相应的功能实现,
- 注意case内部无法定义变量,可以使用 {} 将执行的代码变成代码块。
这种方法可以达到控制的效果,但存在一下弊端 - 当case项过多的时候,会导致switch变等非常长,代码观赏性差
 - 需要每个case项都填入执行代码,不利于错误排查,修改起来繁琐,且容易出错。
代码如下 
#include <string.h>
#include <stdio.h>
void handle_0(void)
{
    printf("sign 0 handle function\r\n");
}
void handle_1(void)
{
    printf("sign 1 handle function\r\n");
}
void handle_2(void)
{
    printf("sign 2 handle function\r\n");
}
void handle_3(void)
{
    printf("sign 3 handle function\r\n");
}
int uart_get_sign(int a) //模拟串口命令接收,模拟为0,1,2,3 共4个指令
{
    static int b = 0;
    b = a%4; 
    return b;
    
}
int main(void)
{
    int receive_sign ;  //模拟接收的信号
    int x = 0;
    
    for(int i = 0; i<10; i++ )
    {
        
        receive_sign = uart_get_sign(x);
        x++;
    switch(receive_sign)
    {
         case 0:
        {
            handle_0();
        }
        break;
        case 1:
        {
            handle_1();
        }
        break;
        case 2:
        {
            handle_2();
        }
        break;
        case 3:
        {
            handle_3();
        }
        break;
       
        default:
            printf(" uart sign error \r\n");
        break;
        
    }
    }
    return 0;
}
使用结构体+指针函数构成处理函数
设计思想
使用一个结构体 结构体内容至少包含
- 串口命令 | 用来识别串口接收的命令
 - 处理函数 | 不同的指令执行相对应的函数
 
结构优势
- 函数清晰明了,循环匹配命令词执行对应处理函数即可
 - bug检查方便,可直接通过数组找那个命令出问题
 
使用结构体数组
代码如下
#include <string.h>
#include <stdio.h>
void info_handle(void)
{
    printf("input info handle\r\n");
}
void x_info_handle(void)
{
    printf("input x info handle\r\n");
}
typedef void (*ack_handle)(void);
typedef struct 
{
    int type ;
    ack_handle handle_func;
}cmd_test;
cmd_test cmd_ack_def[] = {
    {0x11,info_handle},
    {0x12,x_info_handle},
};
int main()
{
    int a = 0x12; //模拟串口接收的数据
    int num = sizeof(cmd_ack_def) / sizeof(cmd_test);
    printf("num = %d\n",num);
    for(int i = 0; i<num ;i++)
    {
        if(a == cmd_ack_def[i].type)
        {
            cmd_ack_def[i].handle_func();
        }
    }
   
   return 0;
}










