Search code examples
c++classinheritancearduinoservo

Arduino servo not working when using wrapper and inheritance


I'm building a robot arm which is quite complicated, so I wrote a class with inheritance to control different servos without having to write too much code. The classes look as follows (some stuff is left out):

In servoPart.h:

#include <Servo.h>

#ifndef SERVO_PART_H
#define SERVO_PART_H

 class ServoPart {
 protected:
      virtual void doJob() = 0;
 private:
      Servo servo;
 public:
      ServoPart(int pin, int minPWM, int maxPWM) {
           servo.attach(pin, minPWM, maxPWM);
      };

      void setAngle(int angle) {
           servo.write(angle);
      };

      int getPosition() {
          return servo.read();
      };
 }
#endif

And in base.h:

#include "servoPart.h"

#ifndef BASE_H
#define BASE_H

class Base : public ServoPart {
private:
    void doJob() {/* implementation */};
public:
    Base(int pin, int stepsize = 5) : ServoPart(pin, 771, 2193) {
    };
};
#endif

And in main.cpp:

#include <Arduino.h>
#include "base.h"

#define SERVO_BASE 9

Base base(SERVO_BASE);

void setup() {
    Serial.begin(9600);
    delay(500);
    base.setAngle(80);
    Serial.println(base.getPosition());    // <-- prints 80
    delay(500);
    base.setAngle(110);
    Serial.println(base.getPosition());    // <-- prints 110
}

void loop() {

}

The servo seems to be set to 80/110, however, nothing moves. If I create the servo object in the main.cpp and use servo.write() there, the servo moves, meaning the problem is not the servo or the connection/circuit. Is it possible that the fault lays in my way of initializing the base? Using Base base(SERVO_BASE) before the setup function?


Solution

  • I found the solution here: When calling servo.attach() in the constructor, the order of variable initialization is messed up. Creating an init() function to be called in setup() solves this problem.