Arduino启动包含类

时间:2016-09-21 17:55:46

标签: arrays class arduino

嗨所以我为一个机器人助行器制作一个层次结构的结构,使伺服的数量可管理,我试图创建一个包含许多伺服类的Limb类(是的,我使用内置的伺服库,但我想要为了校准目的,还要调整偏移量,值的比例等,无论如何,听到的是我的代码。

问题是肢体类发起者(底部4行)我通常不喜欢直接询问正确的代码行并且更喜欢弄明白但是我试过了我能想到的一切

对于任何垃圾拼写而言,我都会对其进行宣传并感谢

class ServoConfig{
  public :
  float Offset;
  float Scale;
  bool Inversed;

  Servo ServoV;

  ServoConfig (float InOffset, float InScale, bool InInversed,int Pin){
      float Offset = InOffset;
      float Scale = InScale;
      bool Inversed = InInversed;
      ServoV.attach(Pin);
  }

  void WriteToServo(float Angle){
    if (Inversed){
      ServoV.write((180-Angle)/Scale + Offset);
    }
    else{
      ServoV.write(Angle/Scale + Offset);
    }  
  }
};

class Limb{

  ServoConfig Servos[];

  Limb (ServoConfig InServos[]){
    ServoConfig Servos[] = InServos;
  }
};

1 个答案:

答案 0 :(得分:0)

在C ++中使用它并不容易,而在Arduino上则更难。

但首先你在代码中有很多错误。例如,阴影类属于局部变量:

ServoConfig (float InOffset, float InScale, bool InInversed,int Pin) {
  float Offset = InOffset;    // this will create new local variable and hides that one in class with the same name
  float Scale = InScale;      // this too
  bool Inversed = InInversed; // and this too

在Limb构造函数中也是如此,但它无论如何都不起作用。

它是如何工作的?你可以使用这样的东西:

#include <Servo.h>

class ServoConfig {
  public :
    float Offset;
    float Scale;
    bool Inversed;

    Servo ServoV;

    ServoConfig (float InOffset, float InScale, bool InInversed,int Pin)
      : Offset   { InOffset   }
      , Scale    { InScale    }
      , Inversed { InInversed }
    {
      ServoV.attach(Pin); // it might have to be attached in setup() as constructors are called before main()
    }

    void WriteToServo(float Angle){
      if (Inversed) {
        ServoV.write((180-Angle)/Scale + Offset);
      } else {
        ServoV.write(Angle/Scale + Offset);
      }  
    }
};

ServoConfig servos[] = {{10,10,0,9},{0,1,0,10}}; // this makes servos of size two and calls constructors

class Limb {
  public:
    ServoConfig * servos_begin;
    ServoConfig * servos_end;

    Limb(ServoConfig * beg, ServoConfig * end)
      : servos_begin { beg }
      , servos_end   { end }
    {;}

    ServoConfig * begin() { return servos_begin;              }
    ServoConfig *   end() { return servos_end;                }
    size_t         size() { return servos_end - servos_begin; }
};

// much better than using  sizeof(array)/sizeof(array[0]):
template <class T, size_t size> size_t arraySize(T(&)[size]) { return size; }

// create and construct Limb instance:
Limb limb { servos, servos + arraySize(servos)};



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

void loop(){
  Serial.println("starting...");

  for (ServoConfig & servo : limb) { // this uses begin() and end() methods
    servo.WriteToServo(90);
  }

  // or directly with array[]
  for (ServoConfig & servo : servos) {
    servo.WriteToServo(40);
  }
}