29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
if(ms < SERVO_MIN_MS)
ms = SERVO_MIN_MS;
softPwmWrite(pin,ms);
}
int main(void)
{
int i;
if(wiringPiSetup() == -1){ //when initialize wiring faiservo,print message to screen
printf("setup wiringPi faiservo !");
return 1;
}
printf("Program is starting ...\n");
servoInit(servoPin); //initialize PWM pin of servo
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);
}
return 0;
}
50 Hz pulse, namely cycle for 20ms, is required to control Servo. In function softPwmCreate (int pin, int
initialValue, int pwmRange), the unit of third parameter pwmRange is 100US, namely 0.1ms. In order to get
the PWM with cycle of 20ms, the pwmRange shoulde be set to 200. So in subfunction of servoInit (), we create
a PWM pin with pwmRange 200.
void servoInit(int pin){ //initialization function for servo PWM pin
softPwmCreate(pin, 0, 200);
}
As 0-180 degrees of servo corresponds to PWM pulse width 0.5-2.5ms, with PwmRange 200 and unit 0.1ms.
So, in function softPwmWrite (int pin, int value), the scope 5-25 of parameter value corresponds to 0-180
degrees of servo. Whatās more, the number writen in subfunction servoWriteMS () should be within the range
of 5-25. However, in practice, due to the manufacture error of each servo, pulse width will also have deviation.
So we define a minimum pulse width and a maximum one and an error offset.