forked from amperka/Troyka-IMU
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lis331dlh.cpp
144 lines (117 loc) · 2.57 KB
/
lis331dlh.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <Arduino.h>
#include <Wire.h>
#include "lis331dlh.h"
#define CTRL_REG1 0x20
#define CTRL_REG1_PM (1 << 5)
#define CTRL_REG4 0x23
#define OUT_X 0x28
#define OUT_Y 0x2A
#define OUT_Z 0x2C
#define ADR_FS_2 0x00
#define ADR_FS_4 0x10
#define ADR_FS_8 0x30
#define SENS_FS_2 0.001
#define SENS_FS_4 0.002
#define SENS_FS_8 0.0039
LIS331DLH_TWI::LIS331DLH_TWI(uint8_t addr)
{
_addr = addr;
_ctrlReg1 = 0x7; // default according to datasheet
}
void LIS331DLH_TWI::begin()
{
Wire.begin();
setRange(RANGE_2);
sleep(false);
_freeFallAcceleration = 9.8;
}
void LIS331DLH_TWI::setRange(uint8_t range)
{
switch (range) {
case RANGE_2: {
_ctrlReg4 = ADR_FS_2;
_mult = SENS_FS_2;
break;
}
case RANGE_4: {
_ctrlReg4 = ADR_FS_4;
_mult = SENS_FS_4;
break;
}
case RANGE_8: {
_ctrlReg4 = ADR_FS_8;
_mult = SENS_FS_8;
break;
}
default: {
_mult = SENS_FS_8;
}
break;
}
writeCtrlReg4();
}
void LIS331DLH_TWI::sleep(bool enable)
{
if (enable)
_ctrlReg1 &= ~CTRL_REG1_PM;
else
_ctrlReg1 |= CTRL_REG1_PM;
writeCtrlReg1();
}
int16_t LIS331DLH_TWI::readX()
{
return readAxis(OUT_X);
}
int16_t LIS331DLH_TWI::readY()
{
return readAxis(OUT_Y);
}
int16_t LIS331DLH_TWI::readZ()
{
return readAxis(OUT_Z);
}
float LIS331DLH_TWI::readX_G()
{
return readX()*_mult*_freeFallAcceleration;
}
float LIS331DLH_TWI::readY_G()
{
return readY()*_mult*_freeFallAcceleration;
}
float LIS331DLH_TWI::readZ_G()
{
return readZ()*_mult*_freeFallAcceleration;
}
int16_t LIS331DLH_TWI::readAxis(uint8_t reg)
{
Wire.beginTransmission(_addr);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(_addr, 1);
while (Wire.available() < 1)
;
uint8_t lowByte = Wire.read();
++reg;
Wire.beginTransmission(_addr);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(_addr, 1);
while (Wire.available() < 1)
;
uint8_t highByte = Wire.read();
return (((int16_t)highByte << 8) | lowByte) >> 4;
}
void LIS331DLH_TWI::writeCtrlReg1()
{
Wire.beginTransmission(_addr);
Wire.write(CTRL_REG1);
Wire.write(_ctrlReg1);
Wire.endTransmission();
}
void LIS331DLH_TWI::writeCtrlReg4()
{
Wire.beginTransmission(_addr);
Wire.write(CTRL_REG4);
Wire.write(_ctrlReg4);
Wire.endTransmission();
}