arduino.ino
1.63 KB
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
int actu = 6;
const int xInput = A0;
const int yInput = A1;
const int zInput = A2;
// initialize minimum and maximum Raw Ranges for each axis
int RawMin = 0;
int RawMax = 1023;
int temp_x = 0;
int temp_y = 0;
int temp_z = 0;
// Take multiple samples to reduce noise
const int sampleSize = 10;
void setup()
{
pinMode(actu,OUTPUT);
analogReference(EXTERNAL);
Serial.begin(115200);
}
void loop()
{
//Read raw values
int xRaw = ReadAxis(xInput)-temp_x;
int yRaw = ReadAxis(yInput)-temp_y;
int zRaw = ReadAxis(zInput)-temp_z;
int result = (abs(xRaw) +abs(yRaw) + abs(zRaw))/3;
temp_x = ReadAxis(xInput);
temp_y = ReadAxis(yInput);
temp_z = ReadAxis(zInput);
// Convert raw values to 'milli-Gs"
long xScaled = map(xRaw, RawMin, RawMax, -3000, 3000);
long yScaled = map(yRaw, RawMin, RawMax, -3000, 3000);
long zScaled = map(zRaw, RawMin, RawMax, -3000, 3000);
// re-scale to fractional Gs
float xAccel = xScaled / 1000.0;
float yAccel = yScaled / 1000.0;
float zAccel = zScaled / 1000.0;
Serial.print("X, Y, Z :: ");
Serial.print(xRaw);
Serial.print(", ");
Serial.print(yRaw);
Serial.print(", ");
Serial.print(zRaw);
Serial.print(" :: ");
Serial.print(xAccel,0);
Serial.print("G, ");
Serial.print(yAccel,0);
Serial.print("G, ");
Serial.print(zAccel,0);
Serial.print("G");
Serial.print(" :: ");
Serial.println(result);
if (result < 0){
result = 0 ;
}
analogWrite(actu,result-3);
delay(50);
}
// Take samples and return the average
int ReadAxis(int axisPin)
{
long reading = 0;
analogRead(axisPin);
delay(1);
for (int i = 0; i < sampleSize; i++)
{
reading += analogRead(axisPin);
}
return reading/sampleSize;
}