tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/pca9685/main.go (about) 1 package main 2 3 import ( 4 "machine" 5 "time" 6 7 "tinygo.org/x/drivers/pca9685" 8 ) 9 10 func main() { 11 const ( 12 // Default address on most breakout boards. 13 pcaAddr = 0x40 14 ) 15 err := machine.I2C0.Configure(machine.I2CConfig{}) 16 if err != nil { 17 panic(err.Error()) 18 } 19 d := pca9685.New(machine.I2C0, 0x40) 20 err = d.IsConnected() 21 if err != nil { 22 panic(err.Error()) 23 } 24 err = d.Configure(pca9685.PWMConfig{Period: 1e9 / 200}) // 200Hz PWM 25 if err != nil { 26 panic(err.Error()) 27 } 28 29 var value uint32 30 step := d.Top() / 5 31 for { 32 for value = 0; value <= d.Top(); value += step { 33 d.SetAll(value) 34 dc := 100 * value / d.Top() 35 println("set dc @", dc, "%") 36 time.Sleep(800 * time.Millisecond) 37 } 38 } 39 } 40 41 // ScanI2CDev finds I2C devices on the bus and rreturns them inside 42 // a slice. If slice is nil then no devices were found. 43 func ScanI2CDev(bus machine.I2C) (addrs []uint8) { 44 var addr, count uint8 45 var err error 46 w := []byte{1} 47 // Count devices in first scan 48 for addr = 1; addr < 127; addr++ { 49 err = bus.Tx(uint16(addr), w, nil) 50 if err == nil { 51 count++ 52 } 53 } 54 if count == 0 { 55 return nil 56 } 57 // Allocate slice and populate slice with addresses 58 addrs = make([]uint8, count) 59 count = 0 60 for addr = 1; addr < 127; addr++ { 61 err = bus.Tx(uint16(addr), w, nil) 62 if err == nil && count < uint8(len(addrs)) { 63 addrs[count] = addr 64 count++ 65 } 66 } 67 return addrs 68 }