如何使用Python控制两个伺服电机,给出事例代码
时间: 2023-03-30 12:01:34 浏览: 607
您好,以下是使用Python控制两个伺服电机的示例代码:
```python
import RPi.GPIO as GPIO
import time
# 设置GPIO模式为BCM
GPIO.setmode(GPIO.BCM)
# 设置引脚号
servo1_pin = 18
servo2_pin = 19
# 设置PWM引脚
GPIO.setup(servo1_pin, GPIO.OUT)
GPIO.setup(servo2_pin, GPIO.OUT)
# 设置PWM频率
pwm1 = GPIO.PWM(servo1_pin, 50)
pwm2 = GPIO.PWM(servo2_pin, 50)
# 启动PWM
pwm1.start()
pwm2.start()
# 控制伺服电机
def set_servo_angle(pwm, angle):
duty_cycle = 2.5 + 10 * angle / 180
pwm.ChangeDutyCycle(duty_cycle)
time.sleep(.3)
# 控制两个伺服电机
try:
while True:
set_servo_angle(pwm1, )
set_servo_angle(pwm2, 90)
set_servo_angle(pwm1, 90)
set_servo_angle(pwm2, )
except KeyboardInterrupt:
pwm1.stop()
pwm2.stop()
GPIO.cleanup()
```
希望对您有所帮助。
阅读全文