I have a machine controlled by DC motors with encoders as position feedback which I am calculating in degrees.
I control the setpoint of where the motors should be with some potentiometers (in degrees). The machine position and setpoint are a float for accuracy, but I am having problems comparing the two values on when to stop the motors (which I understand why) but I have not figured out a way to get past it.
Accuracy only needs to be to 0.2 degrees. So when the machine is within 0.2 degrees of the set point, the motors can stop.
if (setpoint > machinePosistion) //Drive the motor up
{
digitalWrite(DnPin, LOW);
digitalWrite(UpPin, HIGH);
}
else if (setpoint < machinePosistion) //Drive the motor down
{
digitalWrite(DnPin, HIGH);
digitalWritelUpPin, LOW);
}
else if (setpoint == machinePosistion) //Stop the machine
{
digitalWrite(DnPin, LOW);
digitalWrite(UpPin, LOW);
}
}
Basically because of using floats, the setpoint and machinePosistion never equal the same so it over shoots and goes back the other way all the time and hunting.
Do I convert the floats into a long and compare those or is there is more clever way to make this work?
Orac:
The machine position and setpoint are a float for accuracy,
Floats don't give you any accuracy at all! Rather inaccuracy like westfw showed with the epsilon. It you want a accuracy of 0,1 degree, just store the position and set-point as a int values of 1/10 of a degree. So for 10,5 degree you have an int with the value 105. The decimal point can be added later if you want to print it of something. But the calculation of int's is faster and no weird float inaccuracies.
if (abs(setpoint - machinePosition) < EPSILON) { ... }
Define EPSILON as appropriate (but probably not less than about 0.000001...)
(a relatively standard technique.)
Ok I did try something like this, but I think I came into problems when comparing negative numbers. Ie. 0 degrees is machine dead center, --50 degrees is left and +50 degrees is to the right.
Should abs still work correctly in this scenario or maybe I did something wrong..