Go Down

Topic: Using Servo variable as a member variable of my new Servo lib doesn't work (Read 341 times) previous topic - next topic

SteveChang

Hi all,
I want to write a new Servo Class for my project. It needs to wrap the Servo Class provided by Arduino library.  It doesn't work, as there's no driving signal output. Here's my code.
I'd be appreciate if you can give a hand. ( I use Duemilanove 328,  Arduino 1.0.2 IDE, on Win7)

My_ServoDriver_test.h
Code: [Select]
class My_ServoDriver_test
{
public:
My_ServoDriver_test();
My_ServoDriver_test(int portNum);
//pos: 0 -180
void setServoPosition(int pos);

public:
Servo servo;
};


My_ServoDriver_test.cpp
Code: [Select]
#include "My_ServoDriver_test.h"

My_ServoDriver_test::My_ServoDriver_test()
{


}

My_ServoDriver_test::My_ServoDriver_test(int portNum)
{

servo.attach(portNum);

}

void My_ServoDriver_test::setServoPosition(int pos)
{
servo.write(pos);
}


TestServoDriver.ino
Code: [Select]
#include <My_ServoDriver_test.h>
#include <Servo.h>

My_ServoDriver_test servoDriver(11);


void setup()
{
//Serial.begin(9600);
//servoDriver.servo.attach(11);
}

void loop()
{
  servoDriver.setServoPosition(0);
  delay(1000);
  servoDriver.setServoPosition(180);
  delay(1000);

}


If I comment the "servo.attach(portNum); " in the "My_ServoDriver_test::My_ServoDriver_test(int portNum)", and use "servoDriver.servo.attach(11);" in setup(), it works.


PaulS

Quote
If I comment the "servo.attach(portNum); " in the "My_ServoDriver_test::My_ServoDriver_test(int portNum)", and use "servoDriver.servo.attach(11);" in setup(), it works.

Of course. When your constructor is called, the pin is not ready to have a servo attached. But, it goes through the motions.

Then, the init() method gets called, and resets all the pins, to INPUT. A servo on an INPUT pin is kind of useless, don't you think?

When you perform the attach() in setup(), the pin is set as an OUTPUT pin, which lets the servo actually receive some data.

You should NOT be performing hardware-related tasks in a constructor.

Now you know why there is a separate attach() method in the servo class.

Your class should have a begin() method that does the hardware-related stuff. That method should be called in setup().


Go Up