Pages: [1]   Go Down
Author Topic: Using Servo variable as a member variable of my new Servo lib doesn't work  (Read 295 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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:
#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:
#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.

Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48556
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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().
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Got it.
Thank you so much, PaulS.

Logged

Pages: [1]   Go Up
Jump to: