Raspberry Control Servo
Hardware Connection
In this project, the electronic hardware we need to use is as follows:
• Raspberry Pi Pico
• Grove Shield for Pi Pico
• Grove - Servo
Use a Grove data cable to connect Servo to D20. According to the table above, we will try to make the Servo turn back and forth between 45° and 90° .
Write a Program
First, define the required libraries and define the Servo pin.
1 from machine import Pin, PWM
2 from utime import sleep
3
4 pwm_servo = PWM(Pin(20))
5 pwm_servo.freq(100)
Next, rotate the Servo from 0° to 180° ten times using a for-loop. The complete program is as follows:
1 from machine import Pin, PWM
2 from utime import sleep
3
4 pwm_servo = PWM(Pin(20))
5 pwm_servo. freq(100)
6
7 for i in range(10):
8 pwm_servo.duty_u16(7250)
9 sleep(1)
10 pwm_servo.duty_u16(10500)
11 sleep(1)
Running the program, we can see the Servo turns back and forth between 0° and 180° for ten times, which is the effect we want. If we want to control Servo to other angles, we will need to calculate the corresponding value beforehand. If we want to use Servo in other projects, we will also need to redefine the function and the corresponding value. It doesn't seem convenient. For this, we need function libraries. In short, a library file is a file that contains all the functions and variables you define. It can be introduced by other programs to use the functions in the library file. In previous lessons, we used a lot of standard libraries of MicroPython such as machine and utime, and third-party libraries developed by users such as lcd1602 and dht11. In this lesson, we will instead learn to write a simple library file for the Servo to define its pin and rotation angle.