Thank you for your response. I have follow up questions:
I have an accelerometer that outputs values between -1 and 1 for all three axis depending on the orientation of the sensor. When I looked up information about reading accelerometer data, I read that it senses and outputs acceleration data. I'm trying to calculate velocity and displacement with the following expressions:
vx = vx + ax * dt
x = vx * dt
I thought to plug in my x-axis reading into ax and 100ms to dt (my program reads and averages readings in groups of five; each reading is every 20ms).
The data and calculations I'm getting doesn't seem to be working out. The value I'm getting for vx (which is declared as xAvg in the code below) does not reflect the velocity of the sensor, and when the accelerometer is tilted on an axis, the value I'm using for ax increases or decreases depending on the orientation. When the sensor is parallel with the flat surface that it's on, the value from the accelerometer reads 0. The code that I have is below. Any help would be greatly appreciated. Thank you.
#include <Wire.h>
#include <SparkFun_KX13X.h>
SparkFun_KX132 kxAccel;
outputData data;
float x[5];
float xAvg = 0;
float vx = 0;
float ax = 0;
float xPos = 0;
const float dt = 100;
int points = 0;
int i = 0;
void setup() {
Wire.begin();
Serial.begin(115200);
Serial.println("Welcome.");
while (!Serial)
delay(50);
if (!kxAccel.begin()) {
Serial.println("Could not communicate with the the KX13X. Freezing.");
while (1)
;
}
Serial.println("Ready.");
if (kxAccel.softwareReset())
Serial.println("Reset.");
delay(5);
kxAccel.enableAccel(false);
kxAccel.setRange(SFE_KX132_RANGE16G);
kxAccel.enableDataEngine();
kxAccel.enableAccel();
}
void loop() {
if (kxAccel.dataReady()) {
kxAccel.getAccelData(&data);
if (i < 5) {
x[i] = data.xData;
i++;
} else {
for (int ind = 0; ind < 5; ind++) {
xAvg += x[ind];
}
xAvg /= 5;
if (xAvg > -0.02 && xAvg < 0.02) xAvg = 0.0;
vx = vx + xAvg * dt; // vx = vx + ax * dt
xPos = vx * dt // x = vx * dt
Serial.print(xAvg);
Serial.print(", ");
Serial.print(vx);
Serial.print(", ");
Serial.println(xPos);
clearValues();
}
}
delay(20);
}
void clearValues() {
for (int ind = 0; ind < 5; ind++) {
x[ind] = 0;
}
xAvg = 0;
i = 0;
}