树莓派通过16路PCA9685模块驱动舵机
所需材料
- 树莓派
- PCA9685模块
- 舵机(MG995)
模块以及针脚介绍
PCA9685
PCA9685采用I2C总线与主控芯片进行通信,具有可以产生16路PWM脉冲、控制独立精准、编程简单灵活等特点, 以其为基础实现的舵机控制能够有限减少硬件和软件设计的复杂度,具有高可靠性。
连接图
由于舵机功率过大,这里最好单独供电,如图所示
IIC串行总线
控制原理:树莓派利用I2C向寄存器写入值,控制舵机,即使断电也不会影响配置,恢复之后还会是原来的位置。
编写代码
首先导入所需依赖pi4j-core:1.4
、pi4j-gpio-extension:1.3
、slf4j-simple:1.7.32
,测试代码如下
import com.pi4j.gpio.extension.pca.PCA9685GpioProvider;
import com.pi4j.gpio.extension.pca.PCA9685Pin;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CFactory;
import java.math.BigDecimal;
/**
* 〈MCP3008Test〉
*
* @author 丁乾文
* @date 2022/5/25 15:05
* @since 1.0.0
*/
public class PCA9685Test {
public static void main(String[] args) throws Exception {
// 设定舵机控制频率,一般来说是50hz,一个周期20ms
BigDecimal frequency = new BigDecimal("50");
// 设定修正因子,PCA9685的实际输出频率与设定的频率有误差 所以说需要修正,如果必须要纠正只需要填写1就好
BigDecimal frequencyCorrectionFactor = new BigDecimal("1");
I2CBus bus = I2CFactory.getInstance(I2CBus.BUS_1);
// 打开树莓派的IIC功能后获取地址:0x40
final PCA9685GpioProvider pca9685GpioProvider = new PCA9685GpioProvider(bus, 0x40, frequency, frequencyCorrectionFactor);
provisionPwmOutputs(pca9685GpioProvider);
pca9685GpioProvider.reset();
// 转动
pca9685GpioProvider.setPwm(PCA9685Pin.PWM_00, 1600);
System.out.println("Exit");
}
private static void provisionPwmOutputs(final PCA9685GpioProvider gpioProvider) {
GpioController gpio = GpioFactory.getInstance();
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_00, "1");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_01, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_02, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_03, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_04, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_05, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_06, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_07, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_08, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_09, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_10, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_11, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_12, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_13, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_14, "not used");
gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_15, "not used");
}
}
程序执行,则会看到舵机发生了旋转。