Hello everybody,
I am a new to hobby robotics. I have lots of programming experience but not with arduino itself. This is my issue.
I want to turn a servo from 0 degrees to 90 degrees in increments of 2 degrees every 125 milliseconds. After the servo reaches 90 degrees it then goes the other direction back to 0 degrees in increments of 4 degrees every 125 milliseconds. This will just repeat back and forth. I can get it to work as long as I increment the angle in the for loop so that by the time it reaches its minimum or maximum it lands perfectly on 0 or 90 degrees depending on the direction its rotating. Going from 0 degrees I increment the angle every 2 degrees. Rotating back from 90 to 0 degrees, I increment it every 4 degrees. If I do it this way the servo doesnt work properly. When it comes back from 90 to 0 degrees, it hits 0 degrees and then moves back to 90 degrees at full speed and repeats. This is not the behavior I want. It also fails to run through the first if...endif logic section because the turnTo90 boolean variable never gets switched back to true.
I know that if I divide 90 degrees by 4 I get 22.5. As long as my increment amount divided by my total degrees to move gives a division remainder its doesnt work. The only way to fix the problem is to increment by 5 instead of 4. Can anybody tell me why it behaves like this? Any help would greatly be appreciated. Thanks!!
Stuff used:
Arduino Uno
Futaba S3004 180 degree servo
Servo signal in Pin 9 (PWM)
Code:
#include <Servo.h>
Servo calServo;
int servoPin = 9;
boolean turnTo90 = true;
boolean firstRun = true;//True if the program is running thru its first iteration thru the main loop
void setup()
{
//Attach the servo object
calServo.attach(servoPin);
pinMode(debugLEDPin, OUTPUT);
}
void loop()
{
//If this is the first iteration thru the main loop, set the servo to default angle of 0 degrees
if(firstRun)
{
firstRun = false;//Set to false to stop this code from running
calServo.write(0);
}
//Turn the servo from 0 to 90 degrees slowly
if(turnTo90 == true)
{
for(int i = 0; i <= 90; i += 2)
{
//If the servo has reached 90 degrees, start to move the other direction to 0 degrees
if(calServo.read() > 89)
{
turnTo90 = false;
calServo.write(90);//Set the servo to 90 degrees exactly
break;
}
calServo.write(i);
delay(125);
}
}
else if(turnTo90 == false)//Rotate back to 0 degrees faster then from 0 to 90
{
for(int i = 90; i >= 0; i-= 4)
{
//If the servo has reached 0 degrees, start to move the other direction to 90 degrees
if(calServo.read() <= 0)
{
turnTo90 = true;
calServo.write(0);//Set the servo to 0 degrees exactly
break;
}
calServo.write(i);
delay(125);
}
}