Arduino: Putting servos in my class causes them to rotate all the way to one side
- by user2526712
I am trying to create a new class that controls two servos.
My code compiles just fine. However, when I run it, the servos just turn all the way to one direction. This seems to happen when I try instantiating the class (when in the constructor, I attach the servos in the class to pins).
In My class's header file, I have
[UPDATED]
#ifndef ServoController_h
#define ServoController_h
#include "Arduino.h"
#include <Servo.h>
class ServoController
{
public:
ServoController(int rotateServoPin, int elevateServoPin);
void rotate(int degrees);
void elevate(int degrees);
private:
Servo rotateServo;
Servo elevateServo;
int elevationAngle;
int azimuthAngle;
};
#endif
Code so far for my Class:
#include "Arduino.h"
#include "ServoController.h"
ServoController::ServoController(int rotateServoPin, int elevateServoPin)
{
azimuthAngle = 0;
elevationAngle = 0;
elevateServo.attach(elevateServoPin);
rotateServo.attach(rotateServoPin);
}
void ServoController::rotate(int degrees)
{
//TO DO
rotateServo.write(degrees);
}
void ServoController::elevate(int degrees)
{
//TO DO
elevateServo.write(degrees);
}
And finally my arduino sketch so far is just:
#include <ServoController.h>
#include <Servo.h>
ServoController sc(2 , 3);
void setup()
{
}
void loop()
{
}
I'm pretty sure the circuit I am using is fine, since if I do not use my class, and just use the servo library directly in my arduino file, the servos move correctly.
any ideas why this might happen?
[UPDATE]
I actually got this working. In my constructor, I have removed the lines to attach the servos to pins. Instead, I have added another method to my class which does the attachment.
ServoController::ServoController(int rotateServoPin, int elevateServoPin)
{
azimuthAngle = 0;
elevationAngle = 0;
// elevateServo.attach(elevateServoPin);
// rotateServo.attach(rotateServoPin);
}
void ServoController::attachPins(int rotateServoPin, int elevateServoPin)
{
azimuthAngle = 0;
elevationAngle = 0;
elevateServo.attach(elevateServoPin);
rotateServo.attach(rotateServoPin);
}
I then call this in my sketch's setup() function:
void setup()
{
sc.attachPins(2,3);
}
It seems like if I attach my servos outside of the setup() function, my problem occurs.
[UPDATE July 27 9:13PM]
Verified something with another test:
I created a new sketch where I attached a servo before setup():
#include <Servo.h>
Servo servo0;
servo0.attach(2);
void setup()
{
}
void loop() // this function runs repeatedly after setup() finishes
{
servo0.write(90);
delay(2000);
servo0.write(135);
delay(2000);
servo0.write(45);
delay(2000);
}
When I try to compile, Arduino throws an error:
"testservotest:4: error: expected constructor, destructor, or type conversion before '.' token"
So there was an error, but it was not thrown when the attach method was called from a class
Thanks very much