3 @summary pca9685 16路PWM驱动舵机
8 --注意:因使用了sys.wait()所有api需要在协程中使用
15 pca9685=require("pca9685")
20 i2c.setup(i2c_id,i2c.SLOW)
22 pca9685.init(i2c_id,60)
26 pca9685.setpwm(i2c_id,0,i)
48 local PCA_Addr
= 0x40 --pwm通道地址
49 local PCA_Model
=0x00 --工作模式:读1/写0
52 local LED0_OFF_L
= 0x08
53 local LED0_OFF_H
=0x09
56 local function pca9685_write(i2cId
,addr
, data
)
58 ret
=i2c
.send(i2cId
, PCA_Addr
, { addr
, data
})
67 local function pca9685_read(i2cId
,addr
)
68 i2c
.send(i2cId
, PCA_Addr
, addr
)
70 local data
= i2c
.recv(i2cId
,0x40, 1)
79 @api pca9685.init(i2cId,hz)
80 @int i2cid 使用的i2c id, 或者是软件i2c的实例
82 @return 成功返回true 失败返回nil
84 function pca9685
.init(i2cId
,hz
)
86 ret
=pca9685_write(i2cId
,PCA_Model
,0x00)
90 ret
=pca9685
.setfreq(i2cId
,hz
)
94 pca9685
.setpwm(i2cId
,0,0);
95 pca9685
.setpwm(i2cId
,1,0);
96 pca9685
.setpwm(i2cId
,2,0);
97 pca9685
.setpwm(i2cId
,3,0);
98 pca9685
.setpwm(i2cId
,4,0);
99 pca9685
.setpwm(i2cId
,5,0);
100 pca9685
.setpwm(i2cId
,6,0);
101 pca9685
.setpwm(i2cId
,7,0);
102 pca9685
.setpwm(i2cId
,8,0);
103 pca9685
.setpwm(i2cId
,9,0);
104 pca9685
.setpwm(i2cId
,10,0);
105 pca9685
.setpwm(i2cId
,11,0);
106 pca9685
.setpwm(i2cId
,12,0);
107 pca9685
.setpwm(i2cId
,13,0);
108 pca9685
.setpwm(i2cId
,14,0);
109 pca9685
.setpwm(i2cId
,15,0);
117 @api pca9685.setfreq(i2cId,freq)
118 @int i2cid 使用的i2c id, 或者是软件i2c的实例
119 @int freq pca9685的输出频率,范围为24HZ~1526HZ
120 @return 成功返回true 失败返回nil
122 function pca9685
.setfreq(i2cId
,freq
) --PCA9685频率设置
128 prescaleval
= 25000000;
129 prescaleval
= prescaleval
/ 4096
130 prescaleval
= prescaleval
/ freq
131 prescaleval
= prescaleval
- 1
132 prescale
= math
.floor(prescaleval
+ 0.5)
133 oldmode
= string.toHex(pca9685_read(i2cId
,PCA_Model
))
134 newmode
= (oldmode
& 0x7F)|
0x10
135 ret
=pca9685_write(i2cId
,PCA_Model
, newmode
)
139 ret
=pca9685_write(i2cId
,PCA_Pre
, prescale
)
143 ret
=pca9685_write(i2cId
,PCA_Model
, oldmode
)
148 ret
=pca9685_write(i2cId
,PCA_Model
, oldmode|
0xa1)
157 @api pca9685.setpwm(i2cId,num, duty_cycle)
158 @int i2cid 使用的i2c id, 或者是软件i2c的实例
160 @int duty_cycle 占空比 0~100
161 @return 成功返回true 失败返回nil
163 function pca9685
.setpwm(i2cId
,num
, duty_cycle
)
165 if duty_cycle
==50 then
168 on
=math
.floor(4096*((100-duty_cycle
)/100))
170 local off
=on
+math
.floor(4096*(duty_cycle
/100))
171 local ret
= i2c
.send(i2cId
, PCA_Addr
, { LED0_ON_L
+ 4 * num
, on
& 0xFF, on
>> 8, off
& 0xFF, off
>> 8 })