Good day,
I am writing a library for my dc motors. The library will use a pid library. When I create a new dc motor, the constructor of the dc motor library is called. It then should initiate a pid object. How is this generally handled? Where do I declare the pid object?
Thanks
I don’t have the Pid library installed so I just made a dummy class for it. If the constructor of the contained class doesn’t take arguments then this works:
class Pid {
public:
Pid() {
Serial.println("Pid Constructor: ");
}
};
class MotorClass {
public:
MotorClass() {
Serial.println("MotorClass Contructor");
}
private:
Pid internalPidObject;
};
void setup() {
MotorClass *ptr;
Serial.begin(115200);
delay(2000);
Serial.println("Starting");
ptr = new MotorClass;
}
void loop() {}
If it does take arguments, then this:
class Pid {
public:
Pid(uint8_t s) {
Serial.print("Pid Constructor: ");
Serial.println(s);
}
};
class MotorClass {
public:
MotorClass() : internalPidObject(7) {
Serial.println("MotorClass Contructor");
}
private:
Pid internalPidObject;
};
void setup() {
MotorClass *ptr;
Serial.begin(115200);
delay(2000);
Serial.println("Starting");
ptr = new MotorClass;
}
void loop() {}
Note how the Pid() constructor runs BEFORE that of the MotorClass constructor.
Normally, you shouldn't call Serial.print in an Arduino class constructor since the hardware may not be ready yet. But, since I created the object in these examples dynamically with 'new', the constructors will be run after 'steup()'.
Thanks, perfect.
One question: why are you using a pointer to the object?
jacko91:
One question: why are you using a pointer to the object?
So that I could call Serial.print while in the constructor. As I said:
Normally, you shouldn't call Serial.print in an Arduino class constructor since the hardware may not be ready yet. But, since I created the object in these examples dynamically with 'new', the constructors will be run after 'steup()'.