Using servo object inside another object

I’m trying to program an object called motor that has two servos, left and right. In reality these servos are ESC’s that control my left and right motors. When I call right_servo.write(speed) from inside the motor object nothing happens. If I have a global servo object attached to the same pin and write to that, it works! What the heck is wrong? My code is below:

#include <PololuWheelEncoders.h>
#include <Servo.h>

#define ninety 100;

class motors {
private:
  Servo right;
  Servo left;
  PololuWheelEncoders encoder;
public:
  motors() {
    left.attach(5);
    right.attach(6);
    encoder.init(8,9,10,11);
  }

  void drive(short d, short s) {
    short speed = convertSpeed(s);
    short distance = convertDistance(d);
    Serial.print(speed);
    Serial.print(" ");
    Serial.println(distance);
    left.write(speed);
    while(encoder.getCountsM1()<=distance) {
      left.write(speed);
      Serial.println("driving");
    }
    right.write(0);
    resetEncoder();
  }
  void checkEncoder() {
    Serial.print(encoder.getCountsM1());
    Serial.print("\t");
    Serial.println(encoder.getCountsM2());
  }

private:
  void resetEncoder() {
    encoder.getCountsAndResetM1();
    encoder.getCountsAndResetM2();
  }
  int convertSpeed(short s) { //converts speed range
    return map(s, 100, -100, 31, 151);
  }
  int convertDistance(int d) { //converts inches to steps
    return int(d/.125);
  }
};

motors m;

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

void loop() {
  m.drive(2,20);
  m.checkEncoder(); 
}

Thanks for any help!

Constructors for globally declared objects are sketchy business on the Arduino. Don't assume that any of the available libraries are actually available until you are in your setup() function. How to do this?

Move all your construction code to a begin() or init() method of your motor class, then call this method in setup(). I've used the Servo library in my own motor class very similar to what you're attempting, and it works fine, but I don't utilize the class constructors for any initialization. I do it all in init() methods that I call during setup().

#define ninety 100;

Erm …

aside from the WTF, I’m not expecting that to compile. :slight_smile:

    short speed = convertSpeed(s);
  int convertSpeed(short s) { //converts speed range

Oh, yeah. Those two will play well together.