Search code examples
arduinoaccelerometerangle

Why does this angle calculation return only values of 0 or -1?


I am trying to calculate some rough angles on the x-axis from an onboard accelerometer on the light blue bean (https://punchthrough.com/bean/). Issue: Everything I calculate comes back as 0 or -1. So I am obviously either passing something wrong, or converting something wrong. I am unsure what. Thought I would post here to see if anyone has a suggestion. Bean docs say use int16_t but they also sometimes use uint16_t or int. Not sure what to follow. Thanks.

void setup()
{
    Serial.begin(57600);

}

void loop()
{   

    AccelerationReading currentAccel = Bean.getAcceleration(); 

    float xAng = makeXAngles(currentAccel);
    String stringMaster = String();
    stringMaster = stringMaster + "X-Angle: " + xAng;
    Serial.println(stringMaster);
   Bean.sleep(100);
}


float makeXAngles(AccelerationReading one) {

    float x1 = one.xAxis;
    float y1 = one.yAxis;
    float z1 = one.zAxis;


    float x2 = x1 * x1;
    float y2 = y1 * y1;
    float z2 = z1 * z1;

    float result;
    float accel_angle_x;

    // X-Axis
    result = sqrt(y2+z2);
    result = x1/result;
    accel_angle_x = atan(result);

    // return the x angle
    return accel_angle_x;
}

Solution

  • Besides the minor problems, like use of uninitialized variable here int y2 = y1 * y2;, You are using int variables for obviously floating point calculations of the angle, which should be a fractional number in radians (which is hinted by the calculation attempt used). You need to work with float or double precision variables here.