I've got two distance sensors on the sides of a car, and I'm trying to come up with a formula that will attempt to put the car so that it has an equal distance on both sides.
There is an IR sensor on each side of the car which goes from value 0 (infinite distance) to 4096 (up close).
I need to end up with a percentage value to adjust the steering, where 50% is straight ahead, 0% is hard left and 100% is hard right.
A typical scenario is that the left sensor reads 1000, while the right sensor reads 500. In this case I want to turn slightly to the right, probably by setting the turn-percentage to somewhere around 60-70%, and that will turn the steering slightly to the right.
When the car has drifted to the right so that both sensor read the same value the percentage should end up at 50% so that the car keeps going straight.
Any tips on a formula that does this?
UPDATE: I'm seeing that the sensors doesn't actually go all the way down to 0. When the sensor is seeing infinite distance it's actually reading around 600. How can I add this "offset" into my calculations when using WChargin's formula?
How about this?
$$\text{turn percentage} = 100\% \cdot \frac{L}{L + R}$$
where $L$ is the value of the left sensor and $R$ is the value of the right sensor. (You should also the consider the case where $L = R = 0$, in which case the turn percentage should probably be $0.5 = 50\%$.)
For your example, we have $L = 1000$ and $R = 500$, so the turn percentage, according to this formula, would be $\frac{1000}{1000 + 500} = \frac{2}{3} \approx 66\%$, which is right in the range that you specified.
Edit in response to your update. If the actual sensor values don't go down to $0$, then we can create transformed versions that do: $$\begin{align*} L' &\equiv L - 600 & R' &\equiv R - 600. \end{align*}$$ Then, we can treat these transformed values as the original values and use the same formula: $$\text{turn percentage} = 100\% \cdot \frac{L'}{L' + R'}.$$ Note that this will give invalid (negative) values if $L < 600$ or $R < 600$. Perhaps you could find the value of "$600$" at runtime by starting at $600$ and refining this value based on the long-run minimum and maximum.