tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/sht3x/sht3x.go (about) 1 // Package sht3x provides a driver for the SHT3x digital humidity sensor 2 // series by Sensirion. 3 // 4 // Datasheet: 5 // https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/2_Humidity_Sensors/Datasheets/Sensirion_Humidity_Sensors_SHT3x_Datasheet_digital.pdf 6 package sht3x // import "tinygo.org/x/drivers/sht3x" 7 8 import ( 9 "time" 10 11 "tinygo.org/x/drivers" 12 ) 13 14 // Device wraps an I2C connection to a SHT31 device. 15 type Device struct { 16 bus drivers.I2C 17 Address uint16 18 } 19 20 // New creates a new SHT31 connection. The I2C bus must already be 21 // configured. 22 // 23 // This function only creates the Device object, it does not initialize the device. 24 // You must call Configure() first in order to use the device itself. 25 func New(bus drivers.I2C) Device { 26 return Device{ 27 bus: bus, 28 Address: AddressA, 29 } 30 } 31 32 // Read returns the temperature in celsius milli degrees (°C/1000). 33 func (d *Device) ReadTemperature() (tempMilliCelsius int32, err error) { 34 tempMilliCelsius, _, err = d.ReadTemperatureHumidity() 35 return tempMilliCelsius, err 36 } 37 38 // Read returns the relative humidity in hundredths of a percent. 39 func (d *Device) ReadHumidity() (relativeHumidity int16, err error) { 40 _, relativeHumidity, err = d.ReadTemperatureHumidity() 41 return relativeHumidity, err 42 } 43 44 // Read returns both the temperature and relative humidity. 45 func (d *Device) ReadTemperatureHumidity() (tempMilliCelsius int32, relativeHumidity int16, err error) { 46 var rawTemp, rawHum, errx = d.rawReadings() 47 if errx != nil { 48 err = errx 49 return 50 } 51 tempMilliCelsius = (35000 * int32(rawTemp) / 13107) - 45000 52 relativeHumidity = int16(2000 * int32(rawHum) / 13107) 53 return tempMilliCelsius, relativeHumidity, err 54 } 55 56 // rawReadings returns the sensor's raw values of the temperature and humidity 57 func (d *Device) rawReadings() (uint16, uint16, error) { 58 d.bus.Tx(d.Address, []byte{MEASUREMENT_COMMAND_MSB, MEASUREMENT_COMMAND_LSB}, nil) 59 60 time.Sleep(17 * time.Millisecond) 61 62 var data [5]byte 63 d.bus.Tx(d.Address, []byte{}, data[:]) 64 // ignore crc for now 65 66 return readUint(data[0], data[1]), readUint(data[3], data[4]), nil 67 } 68 69 // readUint converts two bytes to uint16 70 func readUint(msb byte, lsb byte) uint16 { 71 return (uint16(msb) << 8) | uint16(lsb) 72 }