Pages: [1]   Go Down
Author Topic: Calculate the minimum angular movement between two compass points?  (Read 271 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Full Member
***
Karma: 1
Posts: 106
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Does anyone have a handy dandy function to do this (returns results from -180 to +180)?
For example:
move from 90 to 180 = 90 (easy)
move from 180 to 90 = -90 (easy)
move from 45 to 359 = -46 (not so easy)
move from 315 to 90 = 135 (not so easy)
(Clockwise move is positive, anti-clock is negative).
Logged

Offline Offline
Edison Member
*
Karma: 19
Posts: 1041
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

function:
Code:
int angDist(int p1, int p2) {
  int rawdist = p2 - p1;
  while (rawdist <  -180) rawdist += 360;
  while (rawdist >= +180) rawdist -= 360;
  return rawdist;
}
and test code:
Code:
#include <iostream>
using namespace std;

int angDist(int p1, int p2) {
  int rawdist = p2 - p1;
  while (rawdist <  -180) rawdist += 360;
  while (rawdist >= +180) rawdist -= 360;
  return rawdist;
}

#define printfunc(x,y) cout << "x: " << x << "y: " << y << "angDist(x, y): " << angDist(x, y) << endl

int main() {
    printfunc(90, 180);
    printfunc(180, 90);
    printfunc(45, 359);
    printfunc(315,90);
}

prints out results you gave
Logged

Offline Offline
Full Member
***
Karma: 1
Posts: 106
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks WizenedEE.  I also found these on the internet which might be of use to others looking for such a function:
Code:
int angle_difference(int target, int head){
  return ((((target - head) % 360) + 540) % 360) - 180;
}

int angleDifference(int target, int head){
  return abs((target + 180 -  head) % 360 - 180);
}
Logged

Pages: [1]   Go Up
Jump to: