1

I've got 2 int16_t numbers, say 388 and 10288, which are sensor readings from an accelerometer. I want to estimate the angle of the device on that, but seemingly there are some type overflow issues:

My final goal is this:

theta =  atan(-ax/sqrt((float)ay*ay+az*az));

The problem occurs in the bracket: ay^2 and az^2 are the 2 power of the given numbers. I recalculated with matlab and for the above example I get a^2+b^2 = 388^2+10288^2 = 105993488 what I get from the arduino however is 152848. To be short: I don't know much about fixed point math or thelike and I couldn't find a sufficient answer to this: How do I calculate the square root term?

1 Answer 1

5

You need 2 typecasts. So

atan(-ax/sqrt((float)ay*ay+(float)az*az));

Otherwise it will use int16_t for the right side of the addition and overflow.

Though for speed you might want to typecast them as long (int32_t), as floats calculations on the arduino are really slow. The sqrt function will covert this double into a float for you.

3
  • Ah, so dumb, thanks! 'theta = atan(-ax /sqrt((uint32_t)ayay +(uint32_t)azaz)) *RAD_TO_DEG;' works! uint, because its squares, which are allways positive^^. Could you however explain to me how sqrt and atan work, when getting an int as input as here? Do they cast automatically? If so, which casts do they do (can I make that obvious by casting myself?)?
    – mike
    Aug 2, 2014 at 18:37
  • sqrt is part of math.h, and it accept a double. A float, in arduino and most cases, is a double. Why it automatically typecasts, I don't know. I would rather expect a compile error, but I don't know C. PS in my question I said double, but meant to say long (fixed in edit).
    – Gerben
    Aug 2, 2014 at 19:40
  • 1
    Because sqrt() and atan() are declared (in math.h) to be functions of double returning double (e.g. double sqrt(double x);), the compiler knows to cast a non-double argument to double before calling the function. Yes, you not only can write the cast explicitly; it is good practice to do so, making clear to the reader that you intended / were aware of the cast.
    – JRobert
    Aug 2, 2014 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.