#define OFFSET_MS 3 //Define the unit of servo pulse offset: 0.1ms
#define SERVO_MIN_MS 5+OFFSET_MS //define the pulse duration for minimum angle of
servo
#define SERVO_MAX_MS 25+OFFSET_MS //define the pulse duration for maximum angle of
servo
……
void servoWriteMS(int pin, int ms){
if(ms > SERVO_MAX_MS)
ms = SERVO_MAX_MS;
if(ms < SERVO_MIN_MS)
ms = SERVO_MIN_MS;
softPwmWrite(pin,ms);
}
In subfunction servoWrite (), input directly angle (0-180 degrees), and map the angle to the pulse width and
then output it.
void servoWrite(int pin, int angle){ //Specif a certain rotation angle (0-180) for the
servo
if(angle > 180)
angle = 180;
if(angle < 0)
angle = 0;
softPwmWrite(pin,map(angle,0,180,SERVO_MIN_MS,SERVO_MAX_MS));
}
Finally, in the "while" cycle of main function, use two "for" cycle to make servo rotate from 0 degrees to 180
degrees, and then from 180 degrees to 0 degrees.
while(1){
for(i=SERVO_MIN_MS;i<SERVO_MAX_MS;i++){ //make servo rotate from minimum angle
to maximum angle
servoWriteMS(servoPin,i);
delay(10);
}
delay(500);
for(i=SERVO_MAX_MS;i>SERVO_MIN_MS;i--){ //make servo rotate from maximum angle
to minimum angle
servoWriteMS(servoPin,i);
delay(10);
}
delay(500);
}