167
Chapter 15 Servo
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
servoWrite
(
dc
)
time
.
sleep
(
0.001
)
time
.
sleep
(
0.5
)
d e f
destroy
():
p
.
stop
()
GPIO
.
cleanup
()
i f
__name__
= =
'__main__'
:
#Program start from here
p r int
(
'Program is starting...'
)
setup
()
t r y
:
loop
( )
e x cept
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
……
d e f
servoWrite
(
angle
):
#make the servo rotate to specific angle (0-180 degrees)
i f
(
angle
<
0
):
angle
=
0
e l if
(
angle
>
180
) :
angle
=
180
p
.
ChangeDutyCycle
(
map
(
angle
,
0
,
180
,
SERVO_MIN_DUTY
,
SERVO_MAX_DUTY
))
Summary of Contents for Ultimate Starter Kit
Page 1: ...Free your innovation Freenove is an open source electronics platform www freenove com ...
Page 117: ...117 Chapter 9 Potentiometer RGBLED www freenove com support freenove com Hardware connection ...
Page 155: ...155 Chapter 14 Relay Motor www freenove com support freenove com Hardware connection OFF 3 3V ...
Page 173: ...173 Chapter 16 Stepping Motor www freenove com support freenove com Hardware connection ...
Page 239: ...239 Chapter 22 Matrix Keypad www freenove com support freenove com Circuit Schematic diagram ...
Page 240: ...Chapter 22 Matrix Keypad 240 www freenove com support freenove com Hardware connection ...