使用RPI.GPIO
创建一个 PWM 实例:
启用 PWM:
更改频率:
更改占空比:
停止 PWM:
但当你同时使用多个舵机时,PWM输出就变得困难了。这时可以借助舵机控制板来进行多路PWM控制。
这是某宝常见的舵机控制板,这个板子也比较便宜,十几块钱一个。使用芯片PCA9685,I2C通信,只需要几根i2c线就可以控制16路pwm,周期和占空比都可控。
驱动板与树莓派连接
GND -> RPi GND(9脚)
SCL -> RPi SCL1(5脚)
SDA -> RPi SDA1(3脚)
VCC -> RPi 3.3V (1脚)
V+ -> RPi 5V(或通过电源接线柱外接电源供电)
需要注意的是,vcc引脚仅为芯片供电,为舵机供电可以选择通过树莓派5v引脚为v+引脚供电或另接电源到驱动板的电源接线柱上。
树莓派开启I2C
树莓派默认关闭I2C,开启I2C步骤:
输入
sudo raspi-config
便可以看到配置界面,
找到第5项:Interfacing Options中有I2C等,点击进入,点击Yes即可
安装adafruit_python_pca9685
sudo pip install adafruit-pca9685
在GitHub上可以查看其例程。
adafruit_pca9685
引入adafruit_pca9685模块:
创建一个 PWM 实例:
设置频率:
更改占空比:
示例代码
# Simple demo of of the PCA9685 PWM servo/LED controller library.
# This will move channel 0 from min to max position repeatedly.
# Author: Tony DiCola
# License: Public Domain
from __future__ import division
import time
# Import the PCA9685 module.
import Adafruit_PCA9685
# Uncomment to enable debug output.
#import logging
#logging.basicConfig(level=logging.DEBUG)
# Initialise the PCA9685 using the default address (0x40).
pwm = Adafruit_PCA9685.PCA9685()
# Alternatively specify a different address and/or bus:
#pwm = Adafruit_PCA9685.PCA9685(address=0x41, busnum=2)
# Configure min and max servo pulse lengths
servo_min = 150 # Min pulse length out of 4096
servo_max = 600 # Max pulse length out of 4096
# Helper function to make setting a servo pulse width simpler.
def set_servo_pulse(channel, pulse):
pulse_length = 1000000 # 1,000,000 us per second
pulse_length //= 60 # 60 Hz
print('{0}us per period'.format(pulse_length))
pulse_length //= 4096 # 12 bits of resolution
print('{0}us per bit'.format(pulse_length))
pulse *= 1000
pulse //= pulse_length
pwm.set_pwm(channel, 0, pulse)
# Set frequency to 60hz, good for servos.
pwm.set_pwm_freq(60)
print('Moving servo on channel 0, press Ctrl-C to quit...')
while True:
# Move servo on channel O between extremes.
pwm.set_pwm(0, 0, servo_min)
time.sleep(1)
pwm.set_pwm(0, 0, servo_max)
time.sleep(1)
如果觉得《树莓派c语言pca9685 使用树莓派控制16路舵机驱动板(pca9685)》对你有帮助,请点赞、收藏,并留下你的观点哦!