I am wrote this simple code to move from one number to another in steps. However, say leaving newPos at 255, I am tearing my hair out over why using certain numbers for currentPos causes it NOT to exit the loop, while some numbers do.
The serial printouts show for every number I tried, that newPos will be equal currentPos on the 10th count, and thus should be exiting the loop but it doesn't with certain numbers.
I have also tried to cast the floats to integers and use the ints in the != statement in case of floating point precision, but the results were still the same.
Whandall:
You should never compare floatingpoint variables for equality,
they simply are not (as you have seen).
Better use somthing like
if (abs(fVal1-fVal2)<0.01) {
Serial.println("near enought");
}
Thanks a lot Whandall, I thought casting it to an integer would solve the floating point issue, apparently not. It works like a charm now. Really appreciate it.
It's just the way floating point works.
It's not exact.
It shows astonishing results if not used with extreme caution.
It's awesome slow on small machines.
Most of the times you can get around having to use it.
Thanks for the tips, I'm not sure if I could think of a shorter code if not using floats. I am currently using this to fade my LEDs using PWM between 2 given values, and it's working really nice and smooth at the moment.
You could use fixed point arithmetics by using fractions as units (1/1024, 1/256, ...)
and shifting / masking the result after computation,
if you need an integer result like for pwm, or color components.
Using integers does not restrict you to the domain of integral values.
Byork:
Thanks for the tips, I'm not sure if I could think of a shorter code if not using floats.
The trick is to use a scale of which 10 and the difference are both common factors. The easiest way to to taht is to multiply the diff by 10, and to add 5 for rounding.
void moveTo(int currentPos, int newPos)
{
int diff = newPos - currentPos;
for(x = 0; x<=diff * 10; x+= diff) {
int pos = currentPos + ((x+5)/10);
}
}