For some reason I simply can't get past this simple problem. I'm using a compass to maintain heading hold. When I press a button it reads the current value in degrees (int holdHeading) and then steers to maintain that heading. Since the compass output is degrees I need to convert each new reading (int currentHeading) into a servo position (int headingError) to steer back to the heading. Simple enough, but when you get in the vicinity of 360 degrees things get messy.
If holdHeading is 359 and currentHeading is 10 then headingError should be 11
if holdHeading is 10 and currentHeading is 359 then headingError should be -11
more simply:
is holdHeading is 180 and currentHeading is 170 then headingError should be -10
if holdHeading is 170 and currentHeading is 180 then headingError should be 10
I'm going to restrict the servo movement to some value like 60 to 120 with 90 being the centered position, but I know how to do that. It's this silly degrees thing that driving me nuts. I seem to have a mental block preventing me from solving something that seems pretty simple.
ponobill:
If holdHeading is 359 and currentHeading is 10 then headingError should be 11
if holdHeading is 10 and currentHeading is 359 then headingError should be -11
The calculations are easier to deal with if you convert heading into the +/- 180 degree range. 359 (from your example) then becomes -1 and so headingError is a simple difference: