# Moving a Robot, Part 2: Heading Issues

So in our previous episode, we discussed how to move a two wheeled robot. However, we mentioned that there’s a problem with computing the angle delta:

$\Delta&space;\phi&space;=&space;\phi_{new}&space;-&space;\phi$

The problem is angle wraparound.

There are two primary ways of representing a heading:  either as an angle in the closed interval [-π, π] or an angle in the closed interval [0, 2π].  If you compute the difference between two angles in either representation, you will likely end up with an angle that is outside the interval due to wraparound, and you will have to correct it.  This correction can be tricky and fraught with peril, since you’ll likely be chasing after special cases.

So, let’s keep it simple, instead.

First, we’ll keep our headings in the interval [-π, π].  Why? Because there’s a nifty trick you can use with the four-quadrant arctangent function, atan2(), that forces any angle to this interval, to wit:

$\phi_{corrected}&space;=&space;\mathrm{atan2}(\sin&space;\phi,&space;\cos&space;\phi)$

Once we’ve corrected $\phi_{new}$ and $\phi$, we compute the difference as usual, plus an additional delta:

$\Delta&space;\phi_1&space;=&space;\phi_{new}&space;-&space;\phi$

$\Delta&space;\phi_2&space;=&space;2&space;\pi&space;-&space;|\Delta&space;\phi_1|$

Now, if $\Delta&space;\phi_1$ is greater than zero, $\Delta&space;\phi_2$ will need to be negated.  Once that is done, we return the appropriate result, based on whether the absolute value of $\Delta&space;\phi_1$ is less than the absolute value of $\Delta&space;\phi_2$.  If it is, we use $\Delta&space;\phi_1$, otherwise, use $\Delta&space;\phi_2$.

When we’re done, we’ll have a properly corrected $\Delta&space;\phi$ that can be used in a controller, or for any other application that requires angle steering.

And that’s it!  Later: all that “real” steering stuff.

This entry was posted in General and tagged , . Bookmark the permalink.