Hi,
I was recently confronted with the exact same problem while building an artificial horizon with an arduino, which is why I am quite into the issue. I know this is really annoying at a first glance, but I have found an elegant solution which I will explain in detail. If you wish me to implement it as well this is not an issue, it's just rewriting my arduino c++ code to java or kotlin.
About me:
I am a software developer who takes part in various IT- and maths-related competitions and reached a federal level in both subjects. I like solving hard problems including 3d movements, rotations and a lot more. I have experience in a variety of platforms (Java, Android, C++, Arduino, Web Development, TensorFlow...).