tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/sht4x/sht4x.go (about) 1 // Package sht4x provides a driver for the SHT4x digital humidity sensor series by Sensirion. 2 // Datasheet: https://www.sensirion.com/media/documents/33FD6951/64D3B030/Sensirion_Datasheet_SHT4x.pdf 3 package sht4x 4 5 import ( 6 "time" 7 8 "tinygo.org/x/drivers" 9 ) 10 11 const DefaultAddress = 0x44 12 13 const ( 14 // single-shot, high-repeatability measurement 15 commandMeasurement = 0xfd 16 ) 17 18 // Device represents a SHT4x sensor 19 type Device struct { 20 bus drivers.I2C 21 Address uint8 22 } 23 24 // New creates a new SHT4x connection. The I2C bus must already be 25 // configured. 26 func New(bus drivers.I2C) Device { 27 return Device{ 28 bus: bus, 29 Address: DefaultAddress, 30 } 31 } 32 33 // ReadTemperatureHumidity starts a measurement and then reads out the results. This function blocks 34 // while the measurement is in progress. 35 // 36 // Temperature is returned in [degree Celsius], multiplied by 1000, 37 // and relative humidity in [percent relative humidity], multiplied by 1000. 38 func (d *Device) ReadTemperatureHumidity() (temperatureMilliCelsius int32, relativeHumidityMilliPercent int32, err error) { 39 rawTemp, rawHum, err := d.rawReadings() 40 if err != nil { 41 return 0, 0, err 42 } 43 44 // from the reference driver: https://github.com/Sensirion/embedded-sht/blob/fcc8a523210cc1241a2750899ff6b0f68f3ed212/sht4x/sht4x.c#L81 45 temperatureMilliCelsius = ((21875 * int32(rawTemp)) >> 13) - 45000 46 relativeHumidityMilliPercent = ((15625 * int32(rawHum)) >> 13) - 6000 47 48 return temperatureMilliCelsius, relativeHumidityMilliPercent, err 49 } 50 51 // rawReadings returns the sensor's raw values of the temperature and humidity 52 func (d *Device) rawReadings() (uint16, uint16, error) { 53 err := d.bus.Tx(uint16(d.Address), []byte{commandMeasurement}, nil) 54 if err != nil { 55 return 0, 0, err 56 } 57 58 // max time for measurement according to datasheet 59 time.Sleep(10 * time.Millisecond) 60 61 var data [6]byte 62 err = d.bus.Tx(uint16(d.Address), nil, data[:]) 63 if err != nil { 64 return 0, 0, err 65 } 66 67 tTicks := readUint(data[0], data[1]) 68 rhTicks := readUint(data[3], data[4]) 69 70 return tTicks, rhTicks, nil 71 } 72 73 // readUint converts two bytes to uint16 74 func readUint(msb byte, lsb byte) uint16 { 75 return (uint16(msb) << 8) | uint16(lsb) 76 }