forked from DavidEGrayson/minimu9-ahrs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathL3G.cpp
86 lines (73 loc) · 1.92 KB
/
L3G.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
#include "L3G.h"
#include <stdexcept>
#define L3G4200D_ADDRESS_SA0_LOW (0xD0 >> 1)
#define L3G4200D_ADDRESS_SA0_HIGH (0xD2 >> 1)
#define L3GD20_ADDRESS_SA0_LOW (0xD4 >> 1)
#define L3GD20_ADDRESS_SA0_HIGH (0xD6 >> 1)
L3G::L3G(const char * i2cDeviceName) : i2c(i2cDeviceName)
{
detectAddress();
}
void L3G::detectAddress()
{
int whoami;
i2c.addressSet(L3G4200D_ADDRESS_SA0_LOW);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD3)
{
// Detected L3G4200D with the SA0 pin low.
return;
}
i2c.addressSet(L3G4200D_ADDRESS_SA0_HIGH);
if (i2c.tryReadByte(L3G_WHO_AM_I) == 0xD3)
{
// Detected L3G4200D with the SA0 pin high.
return;
}
i2c.addressSet(L3GD20_ADDRESS_SA0_LOW);
whoami = i2c.tryReadByte(L3G_WHO_AM_I);
if (whoami == 0xD4)
{
// Detected L3GD20 with the SA0 pin low.
return;
}
if (whoami == 0xD7)
{
// Detected L3GD20H with the SA0 pin low.
return;
}
i2c.addressSet(L3GD20_ADDRESS_SA0_HIGH);
whoami = i2c.tryReadByte(L3G_WHO_AM_I);
if (whoami == 0xD4)
{
// Detected L3GD20 with the SA0 pin high.
return;
}
if (whoami == 0xD7)
{
// Detected L3GD20H with the SA0 pin high.
return;
}
throw std::runtime_error("Could not detect gyro.");
}
// Turns on the gyro and places it in normal mode.
void L3G::enable()
{
writeReg(L3G_CTRL_REG1, 0b00001111); // Normal power mode, all axes enabled
writeReg(L3G_CTRL_REG4, 0b00100000); // 2000 dps full scale
}
void L3G::writeReg(uint8_t reg, uint8_t value)
{
i2c.writeByte(reg, value);
}
uint8_t L3G::readReg(uint8_t reg)
{
return i2c.readByte(reg);
}
void L3G::read()
{
uint8_t block[6];
i2c.readBlock(0x80 | L3G_OUT_X_L, sizeof(block), block);
g[0] = (int16_t)(block[1] << 8 | block[0]);
g[1] = (int16_t)(block[3] << 8 | block[2]);
g[2] = (int16_t)(block[5] << 8 | block[4]);
}