How to determine one variable by the relative values of another?
Question
I'm implementing a PID-control algorithm to a robot I'm currently building using Arduino.
My question is more related to the logics of programming.
I have to calculate a variable, an error, int eps. This eps will be between -7 and +7.
From the robot I acquire an input in the form of a double with values between 0 and 7000.
My algorithm has to work something like this:
if(input >= 500){
if(input >= 1000){
if(input >= 1500){
..........
}
}else{
eps = 6;
}
}else{
eps = 7;
}
And so on...
In other words I have to assign a value to eps that will be determined by which interval the input is included in.
My question is what would be the most efficient, time and resource-saving way of doing this?
I'm using Arduino and their own IDE, not Eclipse.
Solution
If 7 corresponds to 7000 and -7 corresponds to 0, and the intervals between different values of epsilon are equal (500), than you can write eps = static_cast<int>(input/500.0) - 7
. Not sure about static casts in Arduino - you just have to round you value to the lower integer (floor).
If you have some other algorithm of determining eps, please state it more clearly, we'll try to produce math for this;)
OTHER TIPS
The arduino has a map function. http://arduino.cc/en/Reference/map
So you need something like thus; eps = map(input, 0, 7000, -7, +7);
I would say fastest way is:
switch (int(input) / 500)
{
case 0: ... // 0..500
case 1: ... // 500..1000
case 2: ... // 1000..1500
etc
}
It's not entirely clear from your code example what you are trying to achieve, but assuming that you want to evenly distribute your (0 to 7000) input
to the (-7 to 7) eps
values so that all intervals are equally represented you can't use multiples of 500. Using 500s will cause one of the extreme values (-7 or 7) to only result from a very small range of input
values.
You could, for example, use the following function to calculate eps
from input
:
int eps(double input) {
return ((int)(input/500.0)) - 7;
}
However, using this function produces the following mapping which makes an eps
value of 7 much rarer than all the others:
input | eps
>= 0.0 and < 500.0 | -7
>= 500.0 and < 1000.0 | -6
>= 1000.0 and < 1500.0 | -5
>= 1500.0 and < 2000.0 | -4
>= 2000.0 and < 2500.0 | -3
>= 2500.0 and < 3000.0 | -2
>= 3000.0 and < 3500.0 | -1
>= 3500.0 and < 4000.0 | 0
>= 4000.0 and < 4500.0 | 1
>= 4500.0 and < 5000.0 | 2
>= 5000.0 and < 5500.0 | 3
>= 5500.0 and < 6000.0 | 4
>= 6000.0 and < 6500.0 | 5
>= 6500.0 and < 7000.0 | 6
>= 7000.0 | 7
If instead you do want an even distribution, you will need to use the following code:
int eps(double input) {
return ((int)(input/466.733333))-7;
}