# How to choose closest angle when crossing -180 degrees

I'm applying a PID for position control on a diff drive robot, got the angles (orientation )between -pi and pi. It works fine until it needs to change its orientation from (let's say) -170 degrees to 170, when instead of changing its orientation by only 20 degrees it does an entire turn (almost 360) to get to the desired orientation. Does anyone knows how to solve this?

• Welcome to Robotics Leandro Ponce, but I'm afraid that it is not clear what you are asking. We prefer practical, answerable questions based on actual problems that you face, so it's a good idea to include details of what you want to achieve, what you tried, what you saw & what you expected to see. Please take a look at How to Ask & tour for more information on how stack exchange works and work through the Robotics question checklist to edit your question to make it clearer. Mar 16 '21 at 12:19
• It sounds like you want the robot to always choose the smaller angle to rotate, but you have to consider what that means. What is the largest angle the robot should be allowed to turn in one direction? If the magnitude of the calculated angle is larger than the largest allowable angle, how would you offset it? If these hints aren't enough, then again please post what you tried, what you saw, and what you expected to see and we can help you work through your concrete example. Mar 16 '21 at 12:23

This looks like a common angle wrapping mistake. I am assuming you're defining your angles between -180° ($$-\pi$$) to +180° ($$\pi$$).
Since you're defining your angle in the range $$\left[ -180 ; 180 \right]$$, you should also wrap the error in the same range. In the example above, this means removing 360, so the error becomes 340 - 360 = -20. Which is what your PID needs to correct the heading.