Calibrating pitch and roll angles calculated from ADXL345

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?

Would I be correct?

Did it work?

PaulS:
Did it work?

I'll take that as my assumption and math gut being correct.

boylesg:
I'll take that as my assumption and math gut being correct.

You should still validate that assumption by writing the code to implement the assumption and testing it.

If you want accurate results, accelerometers must be calibrated. Adafruit shows you one method but a better one is here .

My method of taking a 100 or so readings from the device in setup with it flat on my desk, averaging them and then subtracting these averages from all future readings seemed to work.

I was getting roll and pitch angles of -1 < 0 < 1 with the device sitting flat on my desk.

That seems good enough to me.

I was trying to come up with a method that does not involve a jig mentioned on the suggested sites and that can be done each time as part of the ADXL345 library.

converting radians to degrees is not done by multiplying by 180!!!