Search code examples
c#mathvectoraccelerometerangle

Find the sign of the angles from an accelerometer


I am using this equation to work out the angles of my x, y and z compared to gravity:

        directionalVector = Math.Sqrt(Math.Pow(accelForceX, 2) + Math.Pow(accelForceY, 2) + Math.Pow(accelForceZ, 2));
        accelAngleX = (Math.Acos(accelForceX / directionalVector) * (180f / Math.PI)); ;
        accelAngleY = (Math.Acos(accelForceY / directionalVector) * (180f / Math.PI));
        accelAngleZ = (Math.Acos(accelForceZ / directionalVector) * (180f / Math.PI));

accelForceN is a reading from an accelerometers axis, measured in G's

This way produces a range of result from 0-180degress, no negative numbers.

How can I find the sign of the angles?


Solution

  • I think you are confused about what you are actually calculating here. Make sure you are aware that you are simply calculating the angle by using the definition of cosinus:

    cos(accelAngleN*2*Math.Pi/360) = accelForceN/directionalVector
    

    (the multiplication with 2Pi/360 merely transforms an angle into Radian). Now consider that the angular sum in a triangle is 180° and thus in this case a negative angle or an angle larger than 180° as result would not make any sense. This is just another way of looking at the fact that cos is not injective over the whole field of real numbers and thus arccos is defined as function on [-1,1] -> [0,Pi] (or [0°,180°] for that matter).

    So what you are currently calculating is the angle of your x/y/z-vectors to your directional vector (rather than to gravity, which would be the z-achsis direction anyways, wouldn't it?) and from this standpoint your output is perfectly valid.

    If you need help with transforming your result any further, please provide an example (2 dimensional should be good enough for the sake of simplicity) of what you are expecting.