我试着写以下函数,
#define CW 0
#define CCW 1
typedef struct
{
uint8_t dir;
uint8_t sr;
uint8_t pwml;
uint8_t en;
uint8_t state;
uint8_t runstate;
uint8_t endstop_status;
} Motor_Params;
Motor_Params Motor_M1;
Motor_Params Motor_M2;
Motor_Params Motor_M3;
Motor_Params Motor_M4;
void Home_Motor(Motor_Params *motor, uint8_t dir)
{
if (dir == CCW)
{
// Start moving motor towards the endstop.
while (motor->endstop_status != 1)
{
if (motor == Motor_M1)
Start_M1_CCW();
else if (motor == Motor_M2)
Start_M2_CCW();
else if (motor == Motor_M3)
Start_M3_CCW();
else if (motor == Motor_M4)
Start_M4_5_CCW();
}
}
}我试图将Motor_Params *motor与它的实例声明进行比较,这样我就可以将这个fn用于多个电机。当我试着编译这个时,我得到,
error: invalid operands to binary == (have 'Motor_Params *' and 'Motor_Params')
if (motor == Motor_M1)如何将Motor_Params *motor与其任何实例声明进行比较?
发布于 2021-02-19 14:10:16
这样的if语句中的比较
if (motor == Motor_M1)一点道理都没有。也就是说,马达是Motor_Params *类型的指针,而Motor_M1是Motor_Params类型的对象。
如果要比较Motor_Params类型的两个对象,则需要根据结构的相等操作的含义,比较结构类型的两个对象的数据成员。也就是说,没有为结构定义内置操作符==。
请注意,当函数定义依赖于全局变量时,这是个坏主意。而不是这些声明
Motor_Params Motor_M1;
Motor_Params Motor_M2;
Motor_Params Motor_M3;
Motor_Params Motor_M4;您可以声明一个数组,例如
Motor_Params Motors[4];并将这个数组作为参数传递给函数。
发布于 2021-02-19 14:10:05
目前,您正在比较指针和实际结构。你必须选择任何一种。
若要比较指针,请将&添加到结构中以获取它们的指针:
if (motor == &Motor_M1)
Start_M1_CCW();
else if (motor == &Motor_M2)
Start_M2_CCW();
else if (motor == &Motor_M3)
Start_M3_CCW();
else if (motor == &Motor_M4)
Start_M4_5_CCW();若要比较结构的值,请将*添加到motor中,以便取消引用:
if (*motor == Motor_M1)
Start_M1_CCW();
else if (*motor == Motor_M2)
Start_M2_CCW();
else if (*motor == Motor_M3)
Start_M3_CCW();
else if (*motor == Motor_M4)
Start_M4_5_CCW();https://stackoverflow.com/questions/66279122
复制相似问题