-
Notifications
You must be signed in to change notification settings - Fork 0
/
Accelerometer.cpp
116 lines (92 loc) · 2.09 KB
/
Accelerometer.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
#include "Arduino.h"
#include "Accelerometer.h"
Accelerometer::Accelerometer(int xInputPin, int yInputPin, int zInputPin) {
analogReference(EXTERNAL);
x = y = z = 0;
deltaX = deltaY = deltaZ = 0;
sampleSize = DEFAULT_SAMPLE_SIZE;
xPin = xInputPin;
yPin = yInputPin;
zPin = zInputPin;
}
int Accelerometer::getX() {
return x;
}
int Accelerometer::getY() {
return y;
}
int Accelerometer::getZ() {
return z;
}
int Accelerometer::getDeltaX() {
return deltaX;
}
int Accelerometer::getDeltaY() {
return deltaY;
}
int Accelerometer::getDeltaZ() {
return deltaZ;
}
int Accelerometer::getAbsDeltaX() {
return abs(getDeltaX());
}
int Accelerometer::getAbsDeltaY() {
return abs(getDeltaY());
}
int Accelerometer::getAbsDeltaZ() {
return abs(getDeltaZ());
}
void Accelerometer::setSampleSize(int newSampleSize) {
if (newSampleSize < 1) {
Serial.print("Invalid accelerometer sample size: ");
Serial.println(newSampleSize);
return;
}
sampleSize = newSampleSize;
}
void Accelerometer::refresh() {
if (!pinsAreValid()) {
Serial.println("WARNING: Accelerometer pins are not configured to valid digital pins");
return;
}
int newX = readAxis(xPin);
int newY = readAxis(yPin);
int newZ = readAxis(zPin);
deltaX = newX - x;
deltaY = newY - y;
deltaZ = newZ - z;
x = newX;
y = newY;
z = newZ;
}
void Accelerometer::debug() {
if (!pinsAreValid()) {
Serial.println("WARNING: Accelerometer pins are not configured to valid digital pins");
return;
}
debugAttitude("Accelerometer orientation: ", x, y ,z);
}
void Accelerometer::debugAttitude(String desc, int x, int y, int z) {
Serial.print(desc);
Serial.print(" X: ");
Serial.print(x);
Serial.print(" Y: ");
Serial.print(y);
Serial.print(" Z: ");
Serial.println(z);
}
//
// Private Members
//
int Accelerometer::readAxis(int axisPin) {
long reading = 0;
analogRead(axisPin);
delay(1);
for (int i = 0; i < sampleSize; i++) {
reading += analogRead(axisPin);
}
return reading / sampleSize;
}
bool Accelerometer::pinsAreValid() {
return (xPin != UNKNOWN_PIN && yPin != UNKNOWN_PIN && zPin != UNKNOWN_PIN);
}