Hello all,
I encountered a very strange problem with my servo motors and I am driving myself nuts trying to solve the issue. Basically, when I uploaded a piece of working code that I previously wrote I am able to drive the servo, so I know for sure that the motor itself, the connection, nor the board are faulty. However when I upload a very simple code that only calls servo.write() method for some reason the servo doesn't move at all and doesn't even make a sound. I made sure the program is executing by serial printing. That made me believe that the only issue is in the code but I just don't understand how it could be different. My old code that works creates a class for writing into the servo but fundamentally I am calling the same method servo.write(). Here is the "simple code" I can't get to work. If I could get any insight that would be greatly appreciated! I am powering the servo using a separate 5V external source and I made sure that the servo is still working by uploading the old code. Thanks!
#include <Servo.h>
Servo myservo;
void setup()
{
Serial.begin(9600);
myservo.attach(2);
}
void loop() {
myservo.write(50);
Serial.print(myservo.read());
delay(1000);
myservo.write(100);
Serial.print(myservo.read());
delay(1000);
}
For your reference, here is the old code that uses class:
--------------Header-----------------
class gripper {
private:
byte pin;
int gripAngle;
int ungripAngle;
public:
Servo servo1;
int currentAngle;
gripper(byte pin);
void init();
void grip();
void ungrip();
void grip(int rate);
void printCurrentAngle();
};
-------------Implmentation-----------
#include "gripper.h"
gripper::gripper(byte pin) {
this->pin = pin;
ungripAngle=80;
gripAngle=10;
}
void gripper::init() {
servo1.attach(pin);
servo1.detach();
}
void gripper::grip() {
servo1.attach(pin);
servo1.write(gripAngle);
delay(500);
printCurrentAngle();
servo1.detach();
}
void gripper::ungrip() {
servo1.attach(pin);
servo1.write(ungripAngle);
delay(500);
printCurrentAngle();
servo1.detach();
}
void gripper::grip(int rate) {
int current = servo1.read();
servo1.attach(pin);
for (int i = current; i >= gripAngle; i--) {
servo1.write(i);
printCurrentAngle();
delay(rate);
}
servo1.detach();
}
void gripper::printCurrentAngle(){
Serial.print("Current Angle: ");
Serial.print(servo1.read());
Serial.print("\t");
}
--------------------------------------