After the above hands-on practice, you already know how to use and run our
course sample code program. Then you must be curious to know how our code
program is programmed on the Raspberry Pi to control the 180° servo. Let's learn
about the main code program together.
1.
import
Adafruit_PCA9685
2.
import
time
Import dependent libraries.
1.
pwm = Adafruit_PCA9685.PCA9685()
2.
pwm.set_pwm_freq(50)
set_pwm_freq(50) is used to set the PWM frequency to 50Hz. This setting
depends on the model of the servo. The servos used in our robot products need to be
controlled by a 50Hz PWM signal. If you use other servos, this A value needs to be
set by referring to the specific servo document.
1.
while
1:
2.
for
in
i
range(0, 100):
3.
pwm.sety_pwm(3, 0, (300+i))
4.
time.sleep(0.05)
5.
for
in
i
range(0,100):
6.
pwm.sety_pwm(3, 0, (400-i))
7.
time.sleep(0.05)
pwm.set_pwm(3, 0, 300+i) This method is used to control the rotation of a servo
to a certain position, where 3 is the port number of the servo, which corresponds to
the number marked on the Robot HAT drive board, but pay attention to the direction
of the ground wire, VCC and signal wire when the servo is connected to the drive
board. Don't plug in the opposite direction. Brown to black, red to red, and yellow to
yellow; 0 is the deviation value that controls the rotation of the servo, 300+i is the
PWM duty cycle value to be set depends on the different servos. This value represents
the angle of the servo. The PWM duty cycle range of the servos we use is about 100
to 560, corresponding to about 0° to 180° Rotation range.
By the formula: (duty ratio -100)/2.55, the angle corresponding to the current
duty ratio can be calculated.
71
Need help?
Do you have a question about the PiCar-Pro and is the answer not in the manual?