-
Notifications
You must be signed in to change notification settings - Fork 109
/
pca9685.go
474 lines (402 loc) · 12 KB
/
pca9685.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//go:build linux
// Package pca9685 implements a PCA9685 HAT. It's probably also a generic PCA9685
// but that has not been verified yet.
package pca9685
import (
"context"
"strconv"
"sync"
"time"
"github.com/edaniels/golog"
"github.com/pkg/errors"
commonpb "go.viam.com/api/common/v1"
pb "go.viam.com/api/component/board/v1"
"go.viam.com/utils"
"go.viam.com/rdk/components/board"
"go.viam.com/rdk/components/board/genericlinux"
"go.viam.com/rdk/grpc"
"go.viam.com/rdk/resource"
)
var model = resource.DefaultModelFamily.WithModel("pca9685")
var (
_ = board.Board(&PCA9685{})
_ = board.GPIOPin(&gpioPin{})
)
// Config describes a PCA9685 board attached to some other board via I2C.
type Config struct {
BoardName string `json:"board_name,omitempty"`
I2CName string `json:"i2c_name,omitempty"`
I2CBus *int `json:"i2c_bus,omitempty"`
I2CAddress *int `json:"i2c_address,omitempty"`
}
// Validate ensures all parts of the config are valid.
func (conf *Config) Validate(path string) ([]string, error) {
var deps []string
// Either the i2c bus or both the board name and i2c name is required.
if conf.I2CBus == nil {
if conf.BoardName == "" && conf.I2CName == "" {
// If all 3 are missing, prefer the i2c_bus approach.
return nil, utils.NewConfigValidationFieldRequiredError(path, "i2c_bus")
}
// Otherwise, we're just missing either the board name or i2c name.
if conf.BoardName == "" {
return nil, utils.NewConfigValidationFieldRequiredError(path, "board_name")
}
if conf.I2CName == "" {
return nil, utils.NewConfigValidationFieldRequiredError(path, "i2c_name")
}
}
if conf.I2CAddress == nil {
conf.I2CAddress = &defaultAddr
}
if *conf.I2CAddress < 0 || *conf.I2CAddress > 255 {
return nil, utils.NewConfigValidationError(path, errors.New("i2c_address must be an unsigned byte"))
}
if conf.BoardName != "" {
deps = append(deps, conf.BoardName)
}
return deps, nil
}
func init() {
resource.RegisterComponent(
board.API,
model,
resource.Registration[board.Board, *Config]{
Constructor: func(
ctx context.Context,
deps resource.Dependencies,
conf resource.Config,
logger golog.Logger,
) (board.Board, error) {
return New(ctx, deps, conf, logger)
},
})
}
// PCA9685 is a general purpose 16-channel 12-bit PWM controller.
type PCA9685 struct {
resource.Named
resource.AlwaysRebuild
resource.TriviallyCloseable
mu sync.RWMutex
address byte
referenceClockSpeed int
bus board.I2C
gpioPins [16]gpioPin
boardName string
i2cName string
logger golog.Logger
}
const (
defaultReferenceClockSpeed = 25000000
mode1Reg = 0x00
prescaleReg = 0xFE
)
// This should be considered const, except you cannot take the address of a const value.
var defaultAddr = 0x40
// New returns a new PCA9685 residing on the given bus and address.
func New(ctx context.Context, deps resource.Dependencies, conf resource.Config, logger golog.Logger) (*PCA9685, error) {
pca := PCA9685{
Named: conf.ResourceName().AsNamed(),
referenceClockSpeed: defaultReferenceClockSpeed,
logger: logger,
}
// each PWM combination spans 4 bytes
startAddr := byte(0x06)
for chanIdx := 0; chanIdx < len(pca.gpioPins); chanIdx++ {
pca.gpioPins[chanIdx].pca = &pca
pca.gpioPins[chanIdx].startAddr = startAddr
startAddr += 4
}
if err := pca.Reconfigure(ctx, deps, conf); err != nil {
return nil, err
}
return &pca, nil
}
// Reconfigure reconfigures the board atomically and in place.
func (pca *PCA9685) Reconfigure(ctx context.Context, deps resource.Dependencies, conf resource.Config) error {
newConf, err := resource.NativeConfig[*Config](conf)
if err != nil {
return err
}
busNum := 0
if newConf.I2CBus != nil {
busNum = *newConf.I2CBus
}
bus, err := genericlinux.GetI2CBus(deps, newConf.BoardName, newConf.I2CName, busNum)
if err != nil {
return err
}
address := byte(*newConf.I2CAddress)
pca.mu.Lock()
defer pca.mu.Unlock()
pca.bus = bus
pca.address = address
pca.boardName = newConf.BoardName
pca.i2cName = newConf.I2CName
if err := pca.reset(ctx); err != nil {
return err
}
return nil
}
func (pca *PCA9685) parsePin(pin string) (int, error) {
pinInt, err := strconv.ParseInt(pin, 10, 32)
if err != nil {
return 0, err
}
if pinInt < 0 || int(pinInt) >= len(pca.gpioPins) {
return 0, errors.Errorf("channel number must be between [0, %d)", len(pca.gpioPins))
}
return int(pinInt), nil
}
// ModelAttributes returns attributes related to the model of this board.
func (pca *PCA9685) ModelAttributes() board.ModelAttributes {
return board.ModelAttributes{}
}
// SetPowerMode sets the board to the given power mode. If provided,
// the board will exit the given power mode after the specified
// duration.
func (pca *PCA9685) SetPowerMode(ctx context.Context, mode pb.PowerMode, duration *time.Duration) error {
return grpc.UnimplementedError
}
// WriteAnalog writes the value to the given pin.
func (pca *PCA9685) WriteAnalog(ctx context.Context, pin string, value int32, extra map[string]interface{}) error {
return grpc.UnimplementedError
}
// Status returns the board status which is always empty.
func (pca *PCA9685) Status(ctx context.Context, extra map[string]interface{}) (*commonpb.BoardStatus, error) {
return &commonpb.BoardStatus{}, nil
}
// GPIOPinByName returns a GPIOPin by name.
func (pca *PCA9685) GPIOPinByName(pin string) (board.GPIOPin, error) {
pinInt, err := pca.parsePin(pin)
if err != nil {
return nil, err
}
if pinInt < 0 || pinInt >= len(pca.gpioPins) {
return nil, errors.New("pin name must be between [0, 16)")
}
return &pca.gpioPins[pinInt], nil
}
// GPIOPinNames returns the names of all known GPIO pins.
func (pca *PCA9685) GPIOPinNames() []string {
return []string{
"0", "1", "2", "3",
"4", "5", "6", "7",
"8", "9", "10", "11",
"12", "13", "14", "15",
}
}
func (pca *PCA9685) openHandle() (board.I2CHandle, error) {
return pca.bus.OpenHandle(pca.address)
}
func (pca *PCA9685) reset(ctx context.Context) error {
handle, err := pca.openHandle()
if err != nil {
return err
}
defer func() {
utils.UncheckedError(handle.Close())
}()
return handle.WriteByteData(ctx, mode1Reg, 0x00)
}
func (pca *PCA9685) frequency(ctx context.Context) (float64, error) {
handle, err := pca.openHandle()
if err != nil {
return 0, err
}
defer func() {
utils.UncheckedError(handle.Close())
}()
prescale, err := handle.ReadByteData(ctx, prescaleReg)
if err != nil {
return 0, err
}
return float64(pca.referenceClockSpeed) / 4096.0 / float64(prescale), nil
}
// SetFrequency sets the global PWM frequency for the pca.
func (pca *PCA9685) SetFrequency(ctx context.Context, frequency float64) error {
pca.mu.RLock()
defer pca.mu.RUnlock()
prescale := byte((float64(pca.referenceClockSpeed) / 4096.0 / frequency) + 0.5)
if prescale < 3 {
return errors.New("invalid frequency")
}
handle, err := pca.openHandle()
if err != nil {
return err
}
defer func() {
utils.UncheckedError(handle.Close())
}()
oldMode1, err := handle.ReadByteData(ctx, mode1Reg)
if err != nil {
return err
}
if err := handle.WriteByteData(ctx, mode1Reg, (oldMode1&0x7F)|0x10); err != nil {
return err
}
if err := handle.WriteByteData(ctx, prescaleReg, prescale); err != nil {
return err
}
if err := handle.WriteByteData(ctx, mode1Reg, oldMode1); err != nil {
return err
}
time.Sleep(5 * time.Millisecond)
if err := handle.WriteByteData(ctx, mode1Reg, oldMode1|0xA0); err != nil {
return err
}
return nil
}
// SPINames returns the names of all known SPIs.
func (pca *PCA9685) SPINames() []string {
return nil
}
// I2CNames returns the names of all known I2Cs.
func (pca *PCA9685) I2CNames() []string {
return nil
}
// AnalogReaderNames returns the names of all known analog readers.
func (pca *PCA9685) AnalogReaderNames() []string {
return nil
}
// DigitalInterruptNames returns the names of all known digital interrupts.
func (pca *PCA9685) DigitalInterruptNames() []string {
return nil
}
// SPIByName returns the SPI by the given name if it exists.
func (pca *PCA9685) SPIByName(name string) (board.SPI, bool) {
return nil, false
}
// I2CByName returns the i2c by the given name if it exists.
func (pca *PCA9685) I2CByName(name string) (board.I2C, bool) {
return nil, false
}
// AnalogReaderByName returns the analog reader by the given name if it exists.
func (pca *PCA9685) AnalogReaderByName(name string) (board.AnalogReader, bool) {
return nil, false
}
// DigitalInterruptByName returns the interrupt by the given name if it exists.
func (pca *PCA9685) DigitalInterruptByName(name string) (board.DigitalInterrupt, bool) {
return nil, false
}
// A gpioPin in PCA9685 is the combination of a PWM's T_on and T_off
// represented as two 12-bit (4096 step) values.
type gpioPin struct {
pca *PCA9685
startAddr byte
}
func (gp *gpioPin) Get(ctx context.Context, extra map[string]interface{}) (bool, error) {
dutyCycle, err := gp.PWM(ctx, extra)
if err != nil {
return false, err
}
return dutyCycle != 0, nil
}
func (gp *gpioPin) Set(ctx context.Context, high bool, extra map[string]interface{}) error {
var dutyCyclePct float64
if high {
dutyCyclePct = 1
}
return gp.SetPWM(ctx, dutyCyclePct, extra)
}
func (gp *gpioPin) PWM(ctx context.Context, extra map[string]interface{}) (float64, error) {
gp.pca.mu.RLock()
defer gp.pca.mu.RUnlock()
handle, err := gp.pca.openHandle()
if err != nil {
return 0, err
}
defer func() {
utils.UncheckedError(handle.Close())
}()
regOnLow := board.I2CRegister{handle, gp.startAddr}
regOnHigh := board.I2CRegister{handle, gp.startAddr + 1}
regOffLow := board.I2CRegister{handle, gp.startAddr + 2}
regOffHigh := board.I2CRegister{handle, gp.startAddr + 3}
onLow, err := regOnLow.ReadByteData(ctx)
if err != nil {
return 0, err
}
onHigh, err := regOnHigh.ReadByteData(ctx)
if err != nil {
return 0, err
}
onVal := uint16(onLow) | (uint16(onHigh) << 8)
if onVal == 0x1000 {
return 1, nil
}
// Off takes up zero steps
offLow, err := regOffLow.ReadByteData(ctx)
if err != nil {
return 0, err
}
offHigh, err := regOffHigh.ReadByteData(ctx)
if err != nil {
return 0, err
}
offVal := uint16(offLow) | (uint16(offHigh) << 8)
return float64(offVal<<4) / 0xffff, nil
}
func (gp *gpioPin) SetPWM(ctx context.Context, dutyCyclePct float64, extra map[string]interface{}) error {
gp.pca.mu.RLock()
defer gp.pca.mu.RUnlock()
dutyCycle := uint16(dutyCyclePct * float64(0xffff))
handle, err := gp.pca.openHandle()
if err != nil {
return err
}
defer func() {
utils.UncheckedError(handle.Close())
}()
regOnLow := board.I2CRegister{handle, gp.startAddr}
regOnHigh := board.I2CRegister{handle, gp.startAddr + 1}
regOffLow := board.I2CRegister{handle, gp.startAddr + 2}
regOffHigh := board.I2CRegister{handle, gp.startAddr + 3}
if dutyCycle == 0xffff {
// On takes up all steps
if err := regOnLow.WriteByteData(ctx, 0x00); err != nil {
return err
}
if err := regOnHigh.WriteByteData(ctx, 0x10); err != nil {
return err
}
// Off takes up zero steps
if err := regOffLow.WriteByteData(ctx, 0x00); err != nil {
return err
}
if err := regOffHigh.WriteByteData(ctx, 0x00); err != nil {
return err
}
return nil
}
// On takes up zero steps
if err := regOnLow.WriteByteData(ctx, 0x00); err != nil {
return err
}
if err := regOnHigh.WriteByteData(ctx, 0x00); err != nil {
return err
}
// Off takes up "dutyCycle" steps
dutyCycle >>= 4
if err := regOffLow.WriteByteData(ctx, byte(dutyCycle&0xff)); err != nil {
return err
}
if err := regOffHigh.WriteByteData(ctx, byte(dutyCycle>>8)); err != nil {
return err
}
return nil
}
func (gp *gpioPin) PWMFreq(ctx context.Context, extra map[string]interface{}) (uint, error) {
gp.pca.mu.RLock()
defer gp.pca.mu.RUnlock()
freqHz, err := gp.pca.frequency(ctx)
if err != nil {
return 0, err
}
return uint(freqHz), nil
}
func (gp *gpioPin) SetPWMFreq(ctx context.Context, freqHz uint, extra map[string]interface{}) error {
gp.pca.mu.RLock()
defer gp.pca.mu.RUnlock()
return gp.pca.SetFrequency(ctx, float64(freqHz))
}