Search code examples
c++headerarduinohardwaremove

Servo is not moving while calling from my own library. Arduino


I made a class called "rudder.cpp" and its "rudder.h" I also have the Arduino main code.

1) Arduino main code: calls the rudder class and move the servo.

2) rudder class: moves the servo from 0 to 180. (copy paste from Sweep code http://arduino.cc/en/Tutorial/Sweep)

3) rudder header: this hold all the definitions in rudder.cpp

My problem is when calling the move method from Rudder class, which is just a copy paste code from the sweep and I have made sure that it is working correctly before using it,

I noticed there is a bad behavior is going on.

1) The servo is getting hot 2) Servo is shaking and not moving smoothly like sweep

Snapshot of the code:

Arduino main file

#include <Servo.h>
Rudder rudder = Rudder();
void setup() 
{ 

}

void loop() 
{ 
    rudder.moveRudder();
}

Rudder.cpp file:

#include "Rudder.h"
#include <Rudder.h>
#include <Servo.h>

Servo myServo;

Rudder::Rudder()
{
       myServo.attach(9);
}

// Sweep code!
//
void Rudder::moveRudder()
{
    for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees 
  {                                  // in steps of 1 degree 
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees 
  {                                
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
}

Rudder.h

#ifndef Rudder_h
#define Rudder_h

#include "Arduino.h"
#include <Servo.h>

class Rudder
{
   Public:
   Rudder();
   moveRudder();
   private:
   Servo myServo;

};

#endif

Solution

  • Problem solved!. It is wired!. I have to attach myServo.attach(9); every time when calling moveRudder()

    So the new code is:

    void Rudder::moveRudder()
    {
       myServo.attach(9);             //Here the solution
    
    
        for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees 
      {                                  // in steps of 1 degree 
        myservo.write(pos);              // tell servo to go to position in variable 'pos' 
        delay(15);                       // waits 15ms for the servo to reach the position 
      } 
      for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees 
      {                                
        myservo.write(pos);              // tell servo to go to position in variable 'pos' 
        delay(15);                       // waits 15ms for the servo to reach the position 
      } 
    }