-
Notifications
You must be signed in to change notification settings - Fork 0
/
ADXL355.cpp
103 lines (83 loc) · 2.59 KB
/
ADXL355.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
#include "ADXL355.h"
void ADXL355::spi_writebyte(byte address, byte toWrite)
{
SPI.beginTransaction(settings);
setCS(true);
SPI.transfer((address << 1) | AXL355__SPI_WRITEBIT);
SPI.transfer(toWrite);
setCS(false);
SPI.endTransaction();
}
byte ADXL355::spi_readbyte(byte address)
{
byte result = 0x0;
SPI.beginTransaction(settings);
setCS(true);
SPI.transfer((address << 1) | AXL355__SPI_READBIT);
result = SPI.transfer(0x00);
setCS(false);
SPI.endTransaction();
return result;
}
void ADXL355::spi_multibyte_read(byte *buf, int buffersize, byte startaddress)
{
SPI.beginTransaction(settings);
setCS(true);
SPI.transfer((byte)((startaddress << 1) | AXL355__SPI_READBIT));
for (int i = 0; i < buffersize; i++) {
buf[i] = SPI.transfer(0x0);
}
setCS(false);
SPI.endTransaction();
}
boolean ADXL355::begin(byte range, byte filter = ADXL355_FILTER_OFF)
{
this->range = range;
pinMode(chipselect, OUTPUT);
if (chipselect2 >= 0) {
pinMode(chipselect2, OUTPUT);
}
digitalWrite(chipselect, LOW);
spi_writebyte(ADXL355__REG_RESET, 0x00);
spi_writebyte(ADXL355__REG_RANGE, range);
spi_writebyte(ADXL355__REG_FILTER, filter);
spi_writebyte(ADXL355__REG_POWER_CONTROL, AXL355__CONST_MEASURE_MODE);
byte adbyte = spi_readbyte(0x00);
digitalWrite(chipselect, HIGH);
return adbyte == 0xAD;
}
void ADXL355::takeSample()
{
byte bytebuf[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
spi_multibyte_read(bytebuf, 9, ADXL355__REG_ACCELEROMETER_DATA_BEGIN);
unsigned long buf[9];
for (int i = 0; i < 9; i++)
buf[i] = (int)bytebuf[i];
axes[0] = (buf[2] | buf[1] << 8 | buf[0] << 16) & 0xFFFFFF;
axes[1] = (buf[5] | buf[4] << 8 | buf[3] << 16) & 0xFFFFFF;
axes[2] = (buf[8] | buf[7] << 8 | buf[6] << 16) & 0xFFFFFF;
long mask = 1;
mask = mask << 23;
for (int i = 0; i < 3; i++) {
if (axes[i] > mask) {
axes[i] = -((mask << 1) - axes[i]);
}
}
}
ADXL355Measurement ADXL355::getSample()
{
long scale = ((long)2 << ((3 - range) + 5)) * 1000;
ADXL355Measurement measure;
measure.x = axes[0] / (1.0 * scale);
measure.y = axes[1] / (1.0 * scale);
measure.z = axes[2] / (1.0 * scale);
return measure;
}
byte ADXL355::getStatus() { return spi_readbyte(ADXL255__REG_STATUS); }
void ADXL355::setCS(bool active)
{
digitalWrite(chipselect, !active);
if (chipselect2 >= 0) {
digitalWrite(chipselect2, !active);
}
}