I am successfully generating sensible looking pitch and roll angles from the data from an ADXL345 - from -90 degrees to +90 degrees.
double Adafruit_ADXL345_Unified::lowPassFilter(double dAxisVal, double dFilteredAxisVal)
{
float fAlpha = 0.5;
return (dAxisVal * fAlpha) + (dFilteredAxisVal * (1.0 - fAlpha));
}
void Adafruit_ADXL345_Unified::getAngles(sensors_event_t &event, int16_t &nPitch, int16_t &nRoll)
{
double dX = 0.0, dY = 0.0, dZ = 0.0;
double dPitch = 0, dRoll = 0;
dX = lowPassFilter(event.acceleration.x, dX);
dY = lowPassFilter(event.acceleration.y, dY);
dZ = lowPassFilter(event.acceleration.z, dZ);
dRoll = (atan2(-dY, dZ) * 180.0);
dPitch = (atan2(dX, sqrt((dY * dY) + (dZ * dZ))) * 180.0);
nRoll = round(dRoll);
nPitch = lround(dPitch);
}
There is a problem however.
If I hold the chip flat on my desk I am getting pitch and roll angles of -31 degrees and 11 degrees.
Which means I have to do some calibration here to get the correct values.
My math gut tells me that I should, in Arduino setup(), I should take a series of readings from the ADXL345 (with it flat on the desk), average them and then subtract these averages from all future readings from the ADXL345.
The assumption of course being that the ADXL345 should theoretically read zero of x and y axes with the device flat on the desk.
Would I be correct?