i am writing some code for handleing a compass sensor to get the value that the robot is off course by. i can tak a value from the sensor from 0 - 359. the problem comes when you are currently heading at 350 degrees or so and the course you should be on is at say 10. the numbers cant be taken away and im not sure how to universaly say "if you are off to the right, turn left a bit" and vice versa. not sure on this one. all ideas apreciated
something like this? (not tested)
doSmartTurn(int curDirection, int newDirection)
{
delta = newDirection - curDirection;
if (0 == delta) return; // no need to turn; better use: if (0 == (delta % 360))
if (delta > 180) turnRight(360 - delta);
else if (delta > 0) turnLeft(delta);
esle if (delta > -180) turnRight(-delta);
else turnLeft(360+delta);
}
I'm not entirely sure that solves the problem but thanks for reply
The idea behind the code is to never turn more than 180 degrees, otherwise it is faster to turn the other way : TurnRight(300) ==TurnLeft(60)
A piece of code like this should be somewhere in your sketch
void loop()
{
...
wantedDir = 10; // or determined some other way e.g. XBEE.Read()
currentDir = compass.ReadDirection(); // or something like that
doSmartTurn(currentDir, wantedDir);
...
}
Of course it can be in another separate function instead of in loop()
I looked at the doSmartTurn() => fixed a bug as directions could be >> 360 and a typo
// version 0.2
doSmartTurn(unsigned int curDirection, unsigned int newDirection)
{
// force directions between 0..359
curDirection %= 360;
newDirection %= 360;
int delta = newDirection - curDirection;
if (0 == delta) return; // no need to turn; // better? if (abs(delta) <= threshold) return; // don't do small angles.
if (delta > 180) turnRight(360 - delta);
else if (delta > 0) turnLeft(delta);
else if (delta > -180) turnRight(-delta);
else turnLeft(360+delta);
}
u....are....a....genius! thankyou so much!!!
Too much honor, just took pencil and paper and played the robot to understand how the behaviour should be and what information was available at any moment. .. Give it a try next time (paper is patient