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

     1  // Package mag3110 implements a driver for the MAG3110 3-axis magnetometer by
     2  // Freescale/NXP.
     3  //
     4  // Datasheet: https://www.nxp.com/docs/en/data-sheet/MAG3110.pdf
     5  package mag3110 // import "tinygo.org/x/drivers/mag3110"
     6  
     7  import (
     8  	"tinygo.org/x/drivers"
     9  	"tinygo.org/x/drivers/internal/legacy"
    10  )
    11  
    12  // Device wraps an I2C connection to a MAG3110 device.
    13  type Device struct {
    14  	bus     drivers.I2C
    15  	Address uint16
    16  }
    17  
    18  // New creates a new MAG3110 connection. The I2C bus must already be
    19  // configured.
    20  //
    21  // This function only creates the Device object, it does not touch the device.
    22  func New(bus drivers.I2C) Device {
    23  	return Device{bus, Address}
    24  }
    25  
    26  // Connected returns whether a MAG3110 has been found.
    27  // It does a "who am I" request and checks the response.
    28  func (d Device) Connected() bool {
    29  	data := []byte{0}
    30  	legacy.ReadRegister(d.bus, uint8(d.Address), WHO_AM_I, data)
    31  	return data[0] == 0xC4
    32  }
    33  
    34  // Configure sets up the device for communication.
    35  func (d Device) Configure() {
    36  	legacy.WriteRegister(d.bus, uint8(d.Address), CTRL_REG2, []uint8{0x80}) // Power down when not used
    37  }
    38  
    39  // ReadMagnetic reads the vectors of the magnetic field of the device and
    40  // returns it.
    41  func (d Device) ReadMagnetic() (x int16, y int16, z int16) {
    42  	legacy.WriteRegister(d.bus, uint8(d.Address), CTRL_REG1, []uint8{0x1a}) // Request a measurement
    43  
    44  	data := make([]byte, 6)
    45  	legacy.ReadRegister(d.bus, uint8(d.Address), OUT_X_MSB, data)
    46  	x = int16((uint16(data[0]) << 8) | uint16(data[1]))
    47  	y = int16((uint16(data[2]) << 8) | uint16(data[3]))
    48  	z = int16((uint16(data[4]) << 8) | uint16(data[5]))
    49  	return
    50  }
    51  
    52  // ReadTemperature reads and returns the current die temperature in
    53  // celsius milli degrees (°C/1000).
    54  func (d Device) ReadTemperature() (int32, error) {
    55  	data := make([]byte, 1)
    56  	legacy.ReadRegister(d.bus, uint8(d.Address), DIE_TEMP, data)
    57  	return int32(data[0]) * 1000, nil
    58  }