IMU angle computation error
Congratulations. You've just discovered that Euler angles are not commutative. Consider the following scenarios. 

You have 3 axes, roll, pitch and yaw. Take a sensor with the reference axis pointing straight up. Now pitch down 90 degrees. The sensor axis is now horizontal. Now rotate horizontally to the right (yaw right) 90 degrees. Your pitch axis is vertical and your reference angle is pointing 90 degrees to the right.
Now do it again, but reverse the order. Yaw 90 degrees to the right, then pitch down 90 degrees. The reference axis is now pointing straight ahead, and the pitch axis is horizontal. You see the problem.

Now try a closed loop.

You have 3 axes, roll, pitch and yaw. Take a sensor with the reference axis pointing straight up. Now rotate vertically 90 degrees. The sensor axis is now horizontal. Pitch angle is -90. Now rotate horizontally to the right 90 degrees. Pitch angle is still -90. Rotate sensor 90 degrees clockwise around the reference axis. Pitch angle is -90. Rotate unit 90 degrees counterclockwise to bring the axis vertical again. The orientation of the unit is restored to its original state, but the pitch reads -90.

Euler angles are not commutative. That is, unlike translations, the order of the rotations matters. It's possible to deal with this but the math is unpleasant (although that's what computers are for). Quaternions are the most general framework to deal with the problem. Look up inertial navigation.