# Math Help

Hi,

I am completely new to arduino but trying to get a motor to move via an Hbridge with the speed related to the values coming from a joystick. I have a line of math that doesn't seem to compute. When I place 255 as the value it reads fine but the following equation always reads zero;

speedLval = ((512-xValue)/512)*255;

xValue will always be between 0 and 462. Am I missing something obvious in the equation?

Paul

You're using integer math and it's getting truncated. This:

``````512-xValue)/512
``````

will be one only if xValue = zero otherwise it will be zero.

use floating point:

`````` ((512.0-xValue)/512.0)*255;
``````

wildbill - Thankyou, this is fantastic. I am certainly getting a result now. It has also got me looking further into int and float calculations.

The trouble now is that the whole thing seems to slow down when it enters this if statement and although initialisation of the if statement is instant when the conditions are met, there is a lag when it exits.

I have read the float calculations are considerably slower than integer calcs, but I cannot figure out how to avoid it. my xValue will always be incoming as an integer.

Any insights?

Thank you,
Paul.

Sounds like a mistake in the sketch. It's hard to be more specific without being able to see the sketch.

Am I missing something obvious in the equation?

Yes, the order of operations matters. You don't need floating point if you use long integers (to avoid overflow) and rearrange the terms:

``````speedLval = 255L*(512-xValue)/512;
``````

which, if you think about it long and hard enough, is pretty much the same as

``````speedLval = (512-xValue)/2;
``````

Korqi:
The trouble now is that the whole thing seems to slow down when it enters this if statement and although initialisation of the if statement is instant when the conditions are met, there is a lag when it exits.

I have read the float calculations are considerably slower than integer calcs,

True, but they are not going to be so much slower that a human is likely to notice it. Something else is going on.

Yes there was something else. Very stupid mistake. I had a blinking LED to indicate weather the IF statement was activated. I am sure you can work out the rest....

Thank you for the replies!
(I will peel the palm of my face now.)