Sorry, I did not read your post closely enough and assumed you were using an accelerometer or IMU (which many people do call a “gyro”).

You will have to think long and hard about how to treat motion about two axes simultaneously. Your computational approach assumes that the angles are independent and additive with regard to 3D orientations, but they are not.

Rotation of 45 degrees about X followed by 45 degrees about Y results in an entirely different orientation than the reverse, or trying to rotate 45 degrees about both axes “simultaneously”.

Then, there is potential confusion about the coordinate system itself: the sensor has its own axes, and rotations it measures are in the sensor (moving) frame of reference, not the external frame of reference.

Furthermore, it is extremely unlikely that even if you did the operation correctly, you could easily reverse such a complex motion, and end up with the starting orientation.

The usual computational approach is to use matrix operations for the compound rotations. You start with the unit matrix I representing the starting **sensor** orientation, then apply successive operations to that for **small** successive changes in the angle about the sensor X and Y axes.

The RX rotation operator looks something like this (t is the small X rotation angle, st, ct are the sine and cosine of that angle)

[ 1 0 0 ]

[0 ct -st]

[0 st ct]

and the RY rotation operator looks something like this (p is the small Y rotation angle)

[cp 0 sp]

[0 1 0]

[-sp 0 cp]

I probably have the signs wrong on the sine terms, but those depend on your choice of convention for a positive rotation anyway.

For a series of tiny steps you multiply these matrices together successively to get the final orientation matrix O, which can finally be decomposed into a set of orientation angles.

O = RXnRYn…RX2RY2RX1RY1I

or the reverse, depending on whether you are considering the reference (fixed) or moving frame of reference.

Using single precision floats, roundoff errors will invalidate this approach after not very many operations.

Finally it is worth noting that the inverse of a rotation operator is represented by the transpose of the matrix corresponding to the forward operation.

There are tutorials on the web covering this stuff, for example https://en.wikibooks.org/wiki/Robotics_Kinematics_and_Dynamics/Description_of_Position_and_Orientation