/* Code based on servo sweep of 180 degree servo motor. This code however uses microSeconds to control servo position. Also
uses millis() instead of delay() to control the speed of sweep. This allows multitasking without worrying about delay blocking
the program. Free to use for anyone and hope it helps with your project.
Servo sould be
1000uS = 0 degrees
1500uS = 90 degress
2000uS = 180 degrees
as seen in this code I had to adjust it for a particular servo and you will probably need to change these values for yours.
*/
#include <Servo.h>
const int servoPin = 9; // Replace with your servo pin
Servo myservo;
unsigned long previousMillis = 0; // Stores the last time the servo position was updated
const int sweepInterval = 5; // Time in milliseconds between servo position updates
int sweepDirection = 1; // 1: forward, -1: backward
int left = 2400; // left limit. Start at 2000
int right = 600; // right limit. Start at 1000
int stepSize = 5; // step size. 10 = 1 degree on this servo
void setup() {
myservo.attach(servoPin);
myservo.writeMicroseconds(1490); // Set initial position at 90 degrees. Start at 1500
delay(1000);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= sweepInterval) {
// Update servo position
int pos = myservo.readMicroseconds();
// Sweep based on direction
if (sweepDirection == 1) {
if (pos < left) {
pos += stepSize; // Increase pulse width by 10 microseconds (forward)
} else {
sweepDirection = -1; // Reverse direction when reaching maximum
}
} else {
if (pos > right) {
pos -= stepSize; // Decrease pulse width by 10 microseconds (backward)
} else {
sweepDirection = 1; // Reverse direction when reaching minimum
}
}
myservo.writeMicroseconds(pos);
previousMillis = currentMillis;
}
}