void setServoPos(int fullCycleTime, Servo serv){
int ServoPos;
int halfCycleTime=fullCycleTime/2;
int currentTime=millis()%fullCycleTime;
if (currentTime<=halfCycleTime) ServoPos= 180LcurrentTime/halfCycleTime;
else ServoPos=180-180L(currentTime-halfCycleTime)/halfCycleTime;
Serial.println(ServoPos);
serv.write(ServoPos);
}
That "setServoPos()" function should be suitable for 'fullCycleTime' up to 32767 milliseconds.
#include <Servo.h>
// Global Variables for SERVO #1
// All of the variables for SERVO #1 could be put in a STRUCT
unsigned int gServo_1_StartTime;
unsigned int gServo_1_Delay;
boolean gServo_1_IsRunning = FALSE;
int gServo_1_Degrees = 0;
Servo gServo_1;
// All of the variables for SERVO #1 could be put in a STRUCT
#define myButton 8;
void setup()
{
gServo_1.attach(9);
}
void loop()
{
// Do something here that sets the ServoRunningFlag to TRUE
// Like Push Button or ?
If ( ( HIGH == DigitalRead( MyButton ) ) && ( gServo_1_IsRunning == FALSE ) )
{
// Enable Servo #1
gServo_1_IsRunning = TRUE;
// Initialize the Starting Time
gServo_1_StartTime = millis();
// Set the Delay between Steps
gServo_1_Delay = 20;l
// Initialize the current location to 0 Degrees
gServo_1_Degrees = 0;
// Call the Servo Move function only when the FLAG is set
If ( Servo_1_IsRunning == TRUE )
{
// Move Servo #1
MoveServo( Servo_1, &gServo_1_IsRunning, &gServo_1_StartTime, gServo_1_Delay, &gServo_1_Degrees );
}
}
}
// Put your Servo Moving Code here
// All variables that are modified by this function are passed by ADDRESS
// This code be moved into the Main Loop if each Servo is controlled differently
void ( Servo myServo, int *MyRunningFlag, unsigned int *myStartTime, unsigned int myDelay, int *myDegrees )
{
// Is this Servo DONE ?
If myDegrees >= 180;
{
// Then TURN OFF the global Running Flag for this servo
*myRunningFlag = FALSE;
}
else
{
// Is it time to advance this servo?
If ( millis() - *myStartTime > myDelay )
{
// Capture the time of the step for this servo
*myStartTime = millis();
// Advance this Servo to the next angle
myServo.pos( *myDegrees );
// Compute the next angle for this servo
*myDegrees++;
}
}
}