Problems with my gyroscope script

Hey everyone

In the script down bellow am I have some problems. The goal of my script is checking on the z-rotation no matter where the Y axis is pointing at . Say, I hold the phone so that I get about 90 degrees of pitch. However, as I turn the phone around the Y axis, it eventually spikes up to 360 degrees and then down to zero, and back to 70. could anyone of you help me with this?

thanks in advance!

Quaternion referenceRotation = Quaternion.identity;
            Quaternion deviceRotation = gyro.attitude;
            Quaternion eliminationOfXY = Quaternion.Inverse(
                Quaternion.FromToRotation(referenceRotation * Vector3.forward,
                                          deviceRotation * Vector3.forward)
            Quaternion rotationZ = eliminationOfXY * deviceRotation;
            float roll = rotationZ.eulerAngles.z;


The doc says the Gyroscope coord system and Unity’s are different and you should use this to translate one into the other.

    // The Gyroscope is right-handed.  Unity is left handed.
    // Make the necessary change to the camera.
    void GyroModifyCamera()
        transform.rotation = GyroToUnity(Input.gyro.attitude);

    private static Quaternion GyroToUnity(Quaternion q)
        return new Quaternion(q.x, q.y, -q.z, -q.w);

Using this, GyroToUnity(Input.gyro.attitude).eulerAngles.z should give you what you want.