Using Servo library inside another library

I'm trying to make a library to control an arm with 5 servos. I would like to use the Servo library inside mine so that I can just call the Servo.write(angle) wherever I need it.

Everything compiles fine with the test code below, but the signal sent to the servos is incorrect. No matter what angle I send it always goes beyond 0 degrees. In other words, it's sending an unreasonably small pulse width.

The only thing I can guess is there is some issue with having the Servo instance in the scope of the class, vs having it as a global as is usually used.

Thanks for the help!

header file


#ifndef Arm_h
#define Arm_h

#include "Servo.h"

class Arm
{
      public:
            Arm();
            void open();
            void close();
      
      private:
            Servo servo;
};

#endif

cpp file


#include <WProgram.h>
#include "Arm.h"

#define SERVO_PIN 9
#define MIN_PW 900
#define MAX_PW 2100
#define CLOSE_ANG 90
#define OPEN_ANG 0
#define DELAY 1000

Arm::Arm()
{
      this->servo.attach(SERVO_PIN, MIN_PW, MAX_PW);
}

void Arm::open()
{
      this->servo.write(OPEN_ANG);
      delay(DELAY);
}

void Arm::close()
{
      this->servo.write(CLOSE_ANG);
      delay(DELAY);
}

pde file


#include <Arm.h>

Arm arm;

void setup()
{
  arm.close();
}

void loop()
{
}

/me

Where did you get your pulse-width values from?

http://www.robotshop.com/PDF/Servomanual.pdf

Using a function instead of the constructor worked. Not sure why.

Thanks!

h file


#ifndef Arm_h
#define Arm_h

#include "Servo.h"

class Arm
{
      public:
            void init();
            void open();
            void close();
      private:
            Servo servo;
};

#endif

cpp file


#include <WProgram.h>
#include "Arm.h"

#define SERVO_PIN 3
#define MIN_PW 900
#define MAX_PW 2100
#define CLOSE_ANG 90
#define OPEN_ANG 0
#define DELAY 1000

void Arm::init()
{
      this->servo.attach(SERVO1_PIN,MIN_PW,MAX_PW);
}      

void Arm::open()
{
      this->servo.write(OPEN_ANG);
      delay(DELAY);
}

void Arm::close()
{
      this->servo.write(CLOSE_ANG);
      delay(DELAY);
}

pde file


#include <Arm.h>

Arm arm;

void setup()
{
  arm.init();
  arm.close();
}

void loop()
{
}

Using a function instead of the constructor worked. Not sure why.

it didn't work because the constructor is called before the Arduino initialization code is called, so the Servo.Attach method did not start properly.

Good to hear you have it going

Alright. Good to know.

/me