tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/lps22hb/lps22hb.go (about) 1 // Package lps22hb implements a driver for LPS22HB, a MEMS nano pressure sensor. 2 // 3 // Datasheet: https://www.st.com/resource/en/datasheet/dm00140895.pdf 4 package lps22hb 5 6 import ( 7 "tinygo.org/x/drivers" 8 "tinygo.org/x/drivers/internal/legacy" 9 ) 10 11 // Device wraps an I2C connection to a HTS221 device. 12 type Device struct { 13 bus drivers.I2C 14 Address uint8 15 } 16 17 // New creates a new LPS22HB connection. The I2C bus must already be 18 // configured. 19 // 20 // This function only creates the Device object, it does not touch the device. 21 func New(bus drivers.I2C) Device { 22 return Device{bus: bus, Address: LPS22HB_ADDRESS} 23 } 24 25 // ReadPressure returns the pressure in milli pascals (mPa). 26 func (d *Device) ReadPressure() (pressure int32, err error) { 27 d.waitForOneShot() 28 29 // read data 30 data := []byte{0, 0, 0} 31 legacy.ReadRegister(d.bus, d.Address, LPS22HB_PRESS_OUT_REG, data[:1]) 32 legacy.ReadRegister(d.bus, d.Address, LPS22HB_PRESS_OUT_REG+1, data[1:2]) 33 legacy.ReadRegister(d.bus, d.Address, LPS22HB_PRESS_OUT_REG+2, data[2:]) 34 pValue := float32(uint32(data[2])<<16|uint32(data[1])<<8|uint32(data[0])) / 4096.0 35 36 return int32(pValue * 1000), nil 37 } 38 39 // Connected returns whether LPS22HB has been found. 40 // It does a "who am I" request and checks the response. 41 func (d *Device) Connected() bool { 42 data := []byte{0} 43 legacy.ReadRegister(d.bus, d.Address, LPS22HB_WHO_AM_I_REG, data) 44 return data[0] == 0xB1 45 } 46 47 // ReadTemperature returns the temperature in celsius milli degrees (°C/1000). 48 func (d *Device) ReadTemperature() (temperature int32, err error) { 49 d.waitForOneShot() 50 51 // read data 52 data := []byte{0, 0} 53 legacy.ReadRegister(d.bus, d.Address, LPS22HB_TEMP_OUT_REG, data[:1]) 54 legacy.ReadRegister(d.bus, d.Address, LPS22HB_TEMP_OUT_REG+1, data[1:]) 55 tValue := float32(int16(uint16(data[1])<<8|uint16(data[0]))) / 100.0 56 57 return int32(tValue * 1000), nil 58 } 59 60 // private functions 61 62 // wait and trigger one shot in block update 63 func (d *Device) waitForOneShot() { 64 // trigger one shot 65 legacy.WriteRegister(d.bus, d.Address, LPS22HB_CTRL2_REG, []byte{0x01}) 66 67 // wait until one shot is cleared 68 data := []byte{1} 69 for { 70 legacy.ReadRegister(d.bus, d.Address, LPS22HB_CTRL2_REG, data) 71 if data[0]&0x01 == 0 { 72 break 73 } 74 } 75 }