36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
time.sleep(0.001)
time.sleep(0.5)
def destroy():
p. stop()
GPIO. cleanup()
if __name__ == '__main__': #Program start from here
p rint ('Program is starting...')
setup()
try:
loop()
e xcept KeyboardInterrupt: # When 'Ctrl+C' is pressed, the subprogram destroy() will
be executed.
destroy()
50 Hz pulse, namely cycle for 20ms, is required to control Servo. So we need set PWM frequency of servoPin
to 50Hz.
p = GPIO. PWM(servoPin, 50) # Set Frequency to 50Hz
As 0-180 degrees of servo corresponds to PWM pulse width 0.5-2.5ms within cycle 20ms and to duty cycle
2.5%-12.5%. In subfunction servoWrite (angle), map the angle to duty cycle to output the PWM, then the servo
will rotate a specific angle. 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.
OFFSE_DUTY = 0.5 #define pulse offset of servo
SERVO_MIN_DUTY = 2.5+ OFFSE_DUTY #define pulse duty cycle for minimum angle of servo
SERVO_MAX_DUTY = 12.5+ OFFSE_DUTY #define pulse duty cycle for maximum angle of servo
ā¦ā¦
def servoWrite(angle): #make the servo rotate to specific angle (0-180 degrees)
if(angle<0):
angle = 0
e lif(angle > 180):
angle = 180
p. ChangeDutyCycle(map(angle,0,180,SERVO_MIN_DUTY,SERVO_MAX_DUTY))