Issues with using Servo.h inside a class

I’ve been trying to create a controller for my quadruped but can’t get the Servo objects from Servo.h to work inside classes.

I’ve written a very simple example to narrow down the problem. This will compile and upload but doesn’t produce any motion.

#include <Servo.h>

class Joint {
  private:
    Servo actuator;
  public:
    Joint(int);
    void setAngle(float);
};

Joint::Joint(int pin) {
  actuator.attach(pin);
}

void Joint::setAngle(float angle) {
  Serial.print(angle);
  actuator.write(angle);
}

Joint joint(36);

void setup() {
  
}

void loop() {
  for (int angle = 45; angle < 135; angle++) {
    joint.setAngle(angle);
    delay(15);
  }
  for (int angle = 135; angle > 45; angle--) {
    joint.setAngle(angle);
    delay(15);
  }
}

Maybe you noticed that this is just like the “Sweep” servo example with the servo inside a special class. Sweep works fine.

I would be very grateful for any help.

Try this:

#include <Servo.h>

class Joint {
  private:
    Servo actuator;
  public:
    Joint(int pin);
    void setAngle(int angle);
};

Joint::Joint(int pin) {
  actuator.attach(pin);
}

void Joint::setAngle(int angle) {
  Serial.print(angle);
  actuator.write(angle);
}

Joint joint(36);

void setup() {
 
}

void loop() {
  for (int angle = 45; angle < 135; angle++) {
    joint.setAngle(angle);
    delay(15);
  }
  for (int angle = 135; angle > 45; angle--) {
    joint.setAngle(angle);
    delay(15);
  }
}

Didn't change anything sadly. The problem really is the Servo object which won't work within a class. Has anyone got any experience with this or managed to implement something like this?

scarafleus:
The problem really is the Servo object which won't work within a class.

I'm pretty sure that's simply untrue.

The first thing I'd try is to remove the call to 'actuator.attach(pin)' from the Joint class's constructor and put it in a begin() method that's called from setup().