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

     1  // Package tmp102 implements a driver for the TMP102 digital temperature sensor.
     2  //
     3  // Datasheet: https://download.mikroe.com/documents/datasheets/tmp102-data-sheet.pdf
     4  
     5  package tmp102 // import "tinygo.org/x/drivers/tmp102"
     6  
     7  import (
     8  	"tinygo.org/x/drivers"
     9  	"tinygo.org/x/drivers/internal/legacy"
    10  )
    11  
    12  // Device holds the already configured I2C bus and the address of the sensor.
    13  type Device struct {
    14  	bus     drivers.I2C
    15  	address uint8
    16  }
    17  
    18  // Config is the configuration for the TMP102.
    19  type Config struct {
    20  	Address uint8
    21  }
    22  
    23  // New creates a new TMP102 connection. The I2C bus must already be configured.
    24  func New(bus drivers.I2C) Device {
    25  	return Device{
    26  		bus: bus,
    27  	}
    28  }
    29  
    30  // Configure initializes the sensor with the given parameters.
    31  func (d *Device) Configure(cfg Config) {
    32  	if cfg.Address == 0 {
    33  		cfg.Address = Address
    34  	}
    35  
    36  	d.address = cfg.Address
    37  }
    38  
    39  // Connected checks if the config register can be read and that the configuration is correct.
    40  func (d *Device) Connected() bool {
    41  	configData := make([]byte, 2)
    42  	err := legacy.ReadRegister(d.bus, d.address, RegConfiguration, configData)
    43  	// Check the reset configuration values.
    44  	if err != nil || configData[0] != 0x60 || configData[1] != 0xA0 {
    45  		return false
    46  	}
    47  	return true
    48  
    49  }
    50  
    51  // Reads the temperature from the sensor and returns it in celsius milli degrees (°C/1000).
    52  func (d *Device) ReadTemperature() (temperature int32, err error) {
    53  
    54  	tmpData := make([]byte, 2)
    55  
    56  	err = legacy.ReadRegister(d.bus, d.address, RegTemperature, tmpData)
    57  
    58  	if err != nil {
    59  		return
    60  	}
    61  
    62  	temperatureSum := int32((int16(tmpData[0])<<8 | int16(tmpData[1])) >> 4)
    63  
    64  	if (temperatureSum & int32(1<<11)) == int32(1<<11) {
    65  		temperatureSum |= int32(0xf800)
    66  	}
    67  
    68  	temperature = temperatureSum * 625
    69  
    70  	return temperature / 10, nil
    71  }