gobot.io/x/gobot/v2@v2.1.0/drivers/i2c/mma7660_driver.go (about) 1 package i2c 2 3 const mma7660DefaultAddress = 0x4c 4 5 const ( 6 MMA7660_X = 0x00 7 MMA7660_Y = 0x01 8 MMA7660_Z = 0x02 9 MMA7660_TILT = 0x03 10 MMA7660_SRST = 0x04 11 MMA7660_SPCNT = 0x05 12 MMA7660_INTSU = 0x06 13 MMA7660_MODE = 0x07 14 MMA7660_STAND_BY = 0x00 15 MMA7660_ACTIVE = 0x01 16 MMA7660_SR = 0x08 17 MMA7660_AUTO_SLEEP_120 = 0x00 18 MMA7660_AUTO_SLEEP_64 = 0x01 19 MMA7660_AUTO_SLEEP_32 = 0x02 20 MMA7660_AUTO_SLEEP_16 = 0x03 21 MMA7660_AUTO_SLEEP_8 = 0x04 22 MMA7660_AUTO_SLEEP_4 = 0x05 23 MMA7660_AUTO_SLEEP_2 = 0x06 24 MMA7660_AUTO_SLEEP_1 = 0x07 25 MMA7660_PDET = 0x09 26 MMA7660_PD = 0x0A 27 ) 28 29 type MMA7660Driver struct { 30 *Driver 31 } 32 33 // NewMMA7660Driver creates a new driver with specified i2c interface 34 // Params: 35 // c Connector - the Adaptor to use with this Driver 36 // 37 // Optional params: 38 // i2c.WithBus(int): bus to use with this driver 39 // i2c.WithAddress(int): address to use with this driver 40 // 41 func NewMMA7660Driver(c Connector, options ...func(Config)) *MMA7660Driver { 42 d := &MMA7660Driver{ 43 Driver: NewDriver(c, "MMA7660", mma7660DefaultAddress), 44 } 45 d.afterStart = d.initialize 46 47 for _, option := range options { 48 option(d) 49 } 50 51 // TODO: add commands for API 52 return d 53 } 54 55 // Acceleration returns the acceleration of the provided x, y, z 56 func (d *MMA7660Driver) Acceleration(x, y, z float64) (ax, ay, az float64) { 57 return x / 21.0, y / 21.0, z / 21.0 58 } 59 60 // XYZ returns the raw x,y and z axis from the mma7660 61 func (d *MMA7660Driver) XYZ() (x float64, y float64, z float64, err error) { 62 buf := []byte{0, 0, 0} 63 bytesRead, err := d.connection.Read(buf) 64 if err != nil { 65 return 66 } 67 68 if bytesRead != 3 { 69 err = ErrNotEnoughBytes 70 return 71 } 72 73 for _, val := range buf { 74 if ((val >> 6) & 0x01) == 1 { 75 err = ErrNotReady 76 return 77 } 78 } 79 80 x = float64((int8(buf[0]) << 2)) / 4.0 81 y = float64((int8(buf[1]) << 2)) / 4.0 82 z = float64((int8(buf[2]) << 2)) / 4.0 83 84 return 85 } 86 87 func (d *MMA7660Driver) initialize() error { 88 if _, err := d.connection.Write([]byte{MMA7660_MODE, MMA7660_STAND_BY}); err != nil { 89 return err 90 } 91 92 if _, err := d.connection.Write([]byte{MMA7660_SR, MMA7660_AUTO_SLEEP_32}); err != nil { 93 return err 94 } 95 96 if _, err := d.connection.Write([]byte{MMA7660_MODE, MMA7660_ACTIVE}); err != nil { 97 return err 98 } 99 100 return nil 101 }