tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/shtc3/shtc3.go (about) 1 // Package shtc3 provides a driver for the SHTC3 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_SHTC3_Datasheet.pdf 6 package shtc3 // import "tinygo.org/x/drivers/shtc3" 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 } 18 19 // New creates a new SHTC3 connection. The I2C bus must already be 20 // configured. 21 // 22 // This function only creates the Device object, it does not initialize the device. 23 // You must call Configure() first in order to use the device itself. 24 func New(bus drivers.I2C) Device { 25 return Device{ 26 bus: bus, 27 } 28 } 29 30 // Read returns the temperature in celsius milli degrees (°C/1000). 31 func (d *Device) ReadTemperature() (tempMilliCelsius int32, err error) { 32 tempMilliCelsius, _, err = d.ReadTemperatureHumidity() 33 return tempMilliCelsius, err 34 } 35 36 // Read returns the relative humidity in hundredths of a percent. 37 func (d *Device) ReadHumidity() (relativeHumidity int16, err error) { 38 _, relativeHumidity, err = d.ReadTemperatureHumidity() 39 return relativeHumidity, err 40 } 41 42 // Read returns both the temperature and relative humidity. 43 func (d *Device) ReadTemperatureHumidity() (tempMilliCelsius int32, relativeHumidity int16, err error) { 44 var rawTemp, rawHum, errx = d.rawReadings() 45 if errx != nil { 46 err = errx 47 return 48 } 49 tempMilliCelsius = ((21875 * int32(rawTemp)) >> 13) - 45000 50 relativeHumidity = int16((1250 * int32(rawHum)) >> 13) 51 return tempMilliCelsius, relativeHumidity, err 52 } 53 54 // rawReadings returns the sensor's raw values of the temperature and humidity 55 func (d *Device) rawReadings() (uint16, uint16, error) { 56 var data [6]byte 57 d.bus.Tx(SHTC3_ADDRESS, []byte(SHTC3_CMD_MEASURE_HP), data[:]) 58 // ignore crc for now 59 return readUint(data[0], data[1]), readUint(data[3], data[4]), nil 60 } 61 62 // WakeUp makes device leave sleep mode 63 func (d *Device) WakeUp() error { 64 d.bus.Tx(SHTC3_ADDRESS, []byte(SHTC3_CMD_WAKEUP), nil) 65 time.Sleep(1 * time.Millisecond) 66 return nil 67 } 68 69 // Sleep makes device go to sleep 70 func (d *Device) Sleep() error { 71 d.bus.Tx(SHTC3_ADDRESS, []byte(SHTC3_CMD_SLEEP), nil) 72 return nil 73 } 74 75 // readUint converts two bytes to uint16 76 func readUint(msb byte, lsb byte) uint16 { 77 return (uint16(msb) << 8) | uint16(lsb) 78 }