embkernel
 All Classes Functions Variables Typedefs Groups Pages
LSM303DLHC.cpp
1 //------------------------------------------------------------------------------
2 //This file is part of embKernel.
3 //See license.txt for the full license governing this code.
4 //------------------------------------------------------------------------------
5 
6 #include "LSM303DLHC.hpp"
7 
8 LSM303DLHC::LSM303DLHC(DrvI2cMaster* i2c) {
9  mI2c = i2c;
10 }
11 
12 LSM303DLHC::~LSM303DLHC() {
13 }
14 
15 void LSM303DLHC::init() {
16  writeMagRegister(LSM303DLHC_CRA_REG_M, LSM303DLHC_TEMPSENSOR_DISABLE | LSM303DLHC_ODR_30_HZ);
17  writeMagRegister(LSM303DLHC_CRB_REG_M, LSM303DLHC_FS_8_1_GA);
18  writeMagRegister(LSM303DLHC_MR_REG_M, LSM303DLHC_CONTINUOS_CONVERSION);
19  writeAccRegister(LSM303DLHC_CTRL_REG1_A, LSM303DLHC_NORMAL_MODE | LSM303DLHC_ODR_50_HZ | LSM303DLHC_AXES_ENABLE); //0x47
20  writeAccRegister(LSM303DLHC_CTRL_REG2_A, LSM303DLHC_HPM_NORMAL_MODE | LSM303DLHC_HPFCF_16 | LSM303DLHC_HPF_AOI1_DISABLE | LSM303DLHC_HPF_AOI2_DISABLE); //0x90
21  writeAccRegister(LSM303DLHC_CTRL_REG4_A, LSM303DLHC_FULLSCALE_2G | LSM303DLHC_BlockUpdate_Continous | LSM303DLHC_BLE_LSB | LSM303DLHC_HR_ENABLE); //0x08
22 }
23 
24 bool LSM303DLHC::readAccXyz(float* x, float* y, float* z) {
25  int16_t xyz[3];
26  if (!readAccRegisters(LSM303DLHC_OUT_X_L_A, (uint8_t*) xyz, sizeof(xyz))) {
27  return false;
28  }
29  *x = (float) xyz[0] / 16000.0;
30  *y = (float) xyz[1] / 16000.0;
31  *z = (float) xyz[2] / 16000.0;
32 
33  return true;
34 }
35 
36 bool LSM303DLHC::writeMagRegister(uint8_t reg, uint8_t value) {
37  mI2c->setSlaveAddr(MAG_I2C_ADDRESS);
38  uint8_t buffer[] = { reg, value };
39  return mI2c->readWrite(buffer, sizeof(buffer), 0, 0);
40 }
41 
42 bool LSM303DLHC::readMagRegisters(uint8_t reg, uint8_t* buffer, size_t len) {
43  if (len > 1) {
44  reg |= 0x80;
45  }
46  mI2c->setSlaveAddr(MAG_I2C_ADDRESS);
47  return mI2c->readWrite(&reg, 1, buffer, len);
48 }
49 
50 bool LSM303DLHC::writeAccRegister(uint8_t reg, uint8_t value) {
51  mI2c->setSlaveAddr(ACC_I2C_ADDRESS);
52  uint8_t buffer[] = { reg, value };
53  return mI2c->readWrite(buffer, sizeof(buffer), 0, 0);
54 }
55 
56 bool LSM303DLHC::readAccRegisters(uint8_t reg, uint8_t* buffer, size_t len) {
57  if (len > 1) {
58  reg |= 0x80;
59  }
60  mI2c->setSlaveAddr(ACC_I2C_ADDRESS);
61  return mI2c->readWrite(&reg, 1, buffer, len);
62 }
63