SunFounder Thales Kit for Raspberry Pi Pico, Release 1.0
4. Connect the yellow lead of the servo to the GP15 pin with a jumper wire.
5. Connect the brawn lead of the servo to the negative power bus with a jumper wire.
Code
When the program is running, we can see the Servo Arm swinging back and forth from 0° to 180°. The program will
always run because of the
while True
loop, we need to press the Stop key to end the program.
import
machine
import
utime
servo
=
machine
.
PWM(machine
.
Pin(
15
))
servo
.
freq(
50
)
def
interval_mapping
(x, in_min, in_max, out_min, out_max):
return
(x
-
in_min)
*
(out_max
-
out_min)
/
(in_max
-
in_min)
+
out_min
def
servo_write
(pin,angle):
pulse_width
=
interval_mapping(angle,
0
,
180
,
0.5
,
2.5
)
duty
=
int
(interval_mapping(pulse_width,
0
,
20
,
0
,
65535
))
pin
.
duty_u16(duty)
while
True
:
for
angle
in
range
(
180
):
servo_write(servo,angle)
utime
.
sleep_ms(
20
)
for
angle
in
range
(
180
,
-
1
,
-
1
):
servo_write(servo,angle)
utime
.
sleep_ms(
20
)
How it works?
We defined the
servo_write()
function to make the servo run.
This function has two parameters:
• pin, the GPIO pin that controls the servo.
• Angle, the angle of the shaft output.
In this function,
interval_mapping()
is called to map the angle range 0 ~ 180 to the pulse width range 0.5 ~
2.5ms.
pulse_width
=
interval_mapping(angle,
0
,
180
,
0.5
,
2.5
)
Why is it 0.5~2.5? This is determined by the working mode of the Servo.
Next, convert the pulse width from period to duty. Since duty_u16() cannot have decimals when used (the value cannot
be a float type), we used
int()
to force the duty to be converted to an int type.
duty
=
int
(interval_mapping(pulse_width,
0
,
20
,
0
,
65535
))
Finally, write the duty value into duty_u16().
3.4. Projects
87
Содержание Thales Kit
Страница 1: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 Jimmy SunFounder Jun 04 2021 ...
Страница 2: ......
Страница 4: ...ii ...
Страница 6: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 2 CONTENTS ...
Страница 10: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 6 Chapter 1 Introduction to Raspberry Pi Pico ...
Страница 12: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 8 Chapter 2 What is Included in This Kit ...
Страница 13: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 2 1 Components List 2 1 Components List 9 ...
Страница 42: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 38 Chapter 2 What is Included in This Kit ...
Страница 140: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 136 Chapter 3 For MicroPython User ...
Страница 164: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 160 Chapter 4 For Arduino User ...