Skip to content

警惕C++里的构造函数 #31

@mysterywolf

Description

@mysterywolf

构造函数里初始化设备这种行为可能会引发一些行为不可控。因为构造函数什么时候初始化并不确定,例如,一旦传感器通过构造函数初始化的时机比IIc设备框架要早,那么,传感器肯定是不工作的。例如:

SmartDrive smd = SmartDrive(SmartDrive_DefaultAddress); //<= 这个函数内部调用了Wire.begin函数, 调用Wire.begin初始化的时候很有可能iic都没有初始化. 因此最好的方法是将其放在setup函数中。

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  //Print on serial monitor
  Serial.print("Motor powered: " + smd.IsMotorPowered(SmartDrive_Motor_ID_1));

  delay(1000);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions