ADXL345's readings is flactuating (How to fix it)

Dear All,

I am building a balancing robot with Raspberry Pi 3. Currently, I am trying to read accelerometer’s tilt angle. I am using the adxl345 and using the SPI protocol. I am able to read the raw x, y, z data. However, my data seems to be fluctuating abit(raw data for x and y is not zero, while z is close to 256 sometimes 230+) while stationary on a flat surface. I had tried out different method including adding the build in offset register, and software offset as taught on this link

I am calculating my pitch and roll based on the below formula

pitch = (atan2(accel.x,sqrt(accel.y*accel.y+accel.z*accel.z)) * 180.0) / PI;
roll = (atan2(accel.y,(sqrt(accel.x*accel.x+accel.z*accel.z))) * 180.0) / PI;

I would also like to mention that, i took the median of 50 raw data before passing it to the calculation of pitch and roll. However, the data still fluctuates. Next, I also tried a averaging filter e.g took the average of 50 raw data before passing it to the calculation of pitch and roll. Similarly, the data still fluctuates. The video posted below does not use software and hardware offset, but include a averaging filter.

Here is aMy Video captured on 16 Feb using raw data only of my calculated pitch and roll fluctuating. This is calculate with raw data only.

The following video shows my attempt to “zero” the data today.
My Video captured on 17 Feb using raw data only
My Video captured on 17 Feb with LPF(Enabled) +HW Offset(Enabled0 + Software Offset(Disabled)

The LPF formula is as such

        float Xg = 0.0, Yg = 0.0, Zg = 0.0;
	Xg = raw_data.x;
	Yg = raw_data.y;
	Zg = raw_data.z;

	//Low Pass Filter - fXg, fYg, & fZg is global variable and stores the new data after filtering
	fXg = Xg * ALPHA + (fXg * (1.0 - ALPHA));
	fYg = Yg * ALPHA + (fYg * (1.0 - ALPHA));
	fZg = Zg * ALPHA + (fZg * (1.0 - ALPHA));

I would like some guidance on whether the behavior in the video I post is normal. I been trying to fix it for few hours to no success. The data is taken while the sensor is stationary and flat on the floor.

Greatly appreciate anyone who had experience with this sensor to assist me. I am trying to achieve high accuracy due to my application.

By the way, is there any know bugged for using SPI for my version, I am using Linux raspberrypi 4.9.28-v7+.

Thank You!

Noise in the readings is perfectly normal, and except that one of the two pitch/roll formulas is wrong, you seem to be taking the correct approach.

Post some examples of the “fluctuations”, before and after averaging, comparing the unaveraged values obtained with the noise levels expected from the specifications in the device data sheet.

For one set of correct definitions for pitch and roll (there are several others), see this page.

For best accuracy, you need to calibrate the accelerometer. Overview here: