Search code examples
blackberryaccelerometerblackberry-jde

Blackberry Accelerometer calculations


I'm playing with the "AccelerometerDemo" in SDK7.0 and have a question regarding the calculation of "rotation" extracted from the XYZ data.

What I want to accomplish is have a virtual "pendulum" that points straight down. However, the thing is gyrating around and does not move as I would expect it.

Here is part of my code:

_accChannel.getLastAccelerationData(_xyz);
double roll = MathUtilities.atan2(X, Z) * 180.0 / Math.PI;

graphics.setColor(Color.BLACK);
int xcenter = 240;
int ycenter = 400;

int length = 220;

int newx1 = (int)(Math.cos( roll ) * (double)length) - xcenter;
int newy1 = (int)(Math.sin( roll ) * (double)length) - ycenter;

graphics.drawLine(xcenter, ycenter, newx1, newy1);

Any clues what I am doing wrong?

Thanks in advance!


Solution

  • I see at least two problems:

    1. Math.cos() and Math.sin() expect angle inputs in radians, not degrees. By using this code:

    double roll = MathUtilities.atan2(X, Z) * 180.0 / Math.PI;
    

    you have converted roll into degrees.

    2. Secondly, you are subtracting the center coordinates from your vector coordinates. I believe you should be adding them, like this:

    int newx1 = (int)(Math.cos( roll ) * (double)length) + xcenter;
    int newy1 = (int)(Math.sin( roll ) * (double)length) + ycenter;