最普通的结构体,反而是使用频率最高的。假设我们要保存一个温控模块的运行参数。初学者很容易把变量全部拆开。float target_temp;
float current_temp;
float kp;
float ki;
float kd;
uint8_t enable;
这样写暂时没问题。等模块越来越多,变量名开始满天飞,函数参数也变成一长串。调用一次初始化函数,像报菜名一样。
void temp_init(float target,
float current,
float kp,
float ki,
float kd,
uint8_t enable);
我看到这种函数声明,心里通常会咯噔一下。参数再加两个,调用者大概率就要传错位置了。把相关数据放进一个结构体,代码立刻清爽很多。
typedef struct
{
float target_temp;
float current_temp;
float kp;
float ki;
float kd;
uint8_t enable;
} TempController_t;
初始化函数也可以改成下面这样。
void temp_controller_init(TempController_t *controller)
{
controller->target_temp = 25.0f;
controller->current_temp = 0.0f;
controller->kp = 1.2f;
controller->ki = 0.05f;
controller->kd = 0.01f;
controller->enable = 1U;
}
结构体真正解决的,不只是少写几个参数。它把一组具有共同生命周期和共同业务含义的数据,变成了一个整体。以后要增加限温值、报警状态、滤波参数,不需要把几十个函数接口全部改一遍。
typedef struct
{
float target_temp;
float current_temp;
float kp;
float ki;
float kd;
float max_temp;
float min_temp;
uint8_t enable;
uint8_t alarm;
} TempController_t;
做嵌入式久了会发现,函数参数数量一旦超过五六个,就该认真考虑结构体了。 |
|