6

I am trying to move a robot using a compass. We use the compass to make the robot move in straight line, it uses 2 wheels and they move a bit different. So we set a value between 0 and 359 as direction, and then check the current direction, calculate the error and fix it. Like error = current_direction - actual direction.

The problem is that if for example our init direction is 90 degrees and our robot is at 45, the error will be 45 and it will fix it. If it is 0, the error will be 90 and it will fix it. The problem is that if it moves a bit more than 0 and it goes for example to 359, the error will be -269 so instead of moving 90 in one direction it will move -269 in the other.

I use the sign of the error to decide which wheel to move to fix the direction. any idea how to fix it?

Dr Sokoban
  • 1,510
  • 3
  • 17
  • 30

4 Answers4

6
if (error > 180) {
   error -= 360;
}

if (error < -180) {
   error += 360;
}
Piskvor left the building
  • 87,797
  • 43
  • 170
  • 220
2

if your error is greater than 180°, you should rack it from 360 and invert the sign. Doing so, you can be sure your robot will always move in the shortest direction.

Tokk
  • 4,310
  • 2
  • 25
  • 44
1

If your error is > than 180 degree simply switch your correction algorithm to calculate the correction by moving in the opposite direction. A simple if-else statement should do.

S73417H
  • 2,551
  • 2
  • 21
  • 36
1

I don't know much about NXT and Mindstorm, but basically it is a common problem in circular motions. You could simply use two different coordinate systems and translate between each other, thats the most elegant way. Otherwise you could subtract 360 from your error, if the sign is negative, but that's a hack and not an elegant way to solve the problem ;-)

tamasgal
  • 20,852
  • 15
  • 87
  • 129
  • Hmmm, polar coordinates? Elegant, but I'd think it might be slower to calculate (esp. on an embedded platform). – Piskvor left the building Apr 05 '11 at 13:14
  • Yes, you could be right, since embedded things are mostly highly hacked things, but I don't think NXT is _such embedded_ ;-) – tamasgal Apr 05 '11 at 13:20
  • 2
    I was thinking in terms of CPU speed and all that comes with it. Although I'm not very familiar with the architecture, I wouldn't think that NXT has a quad-core i5 @ 2.8GHz, right? I'd guess the speed would be in tens of MHz, hundreds at the max. Yes, that's more than my computer had twenty years ago, but you still have to take performance seriously under such constraints. – Piskvor left the building Apr 05 '11 at 13:32