tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/dht/device.go (about)

     1  package dht
     2  
     3  import (
     4  	"encoding/binary"
     5  )
     6  
     7  // DeviceType is the enum type for device type
     8  type DeviceType uint8
     9  
    10  const (
    11  	DHT11 DeviceType = iota
    12  	DHT22
    13  )
    14  
    15  // extractData parses information received from the sensor.
    16  // The 2 first buffers are for the humidity and
    17  // the 2 following corresponds to the temperature.
    18  func (d DeviceType) extractData(buf []byte) (temp int16, hum uint16) {
    19  	switch d {
    20  	case DHT11:
    21  		hum = 10*uint16(buf[0]) + uint16(buf[1])
    22  		temp = int16(buf[2])
    23  		if buf[3]&0x80 > 0 {
    24  			temp = -1 - temp
    25  		}
    26  		temp *= 10
    27  		temp += int16(buf[3] & 0x0f)
    28  	case DHT22:
    29  		hum = binary.BigEndian.Uint16(buf[0:2])
    30  		temp = int16(buf[2]&0x7f)<<8 + int16(buf[3])
    31  		// the first bit corresponds to the sign bit
    32  		if buf[2]&0x80 > 0 {
    33  			temp = -temp
    34  		}
    35  	default:
    36  		// keeping this for retro-compatibility but not tested
    37  		hum = binary.LittleEndian.Uint16(buf[0:2])
    38  		temp = int16(buf[3])<<8 + int16(buf[2]&0x7f)
    39  		if buf[2]&0x80 > 0 {
    40  			temp = -temp
    41  		}
    42  	}
    43  	return
    44  }