Skip to content

Instantly share code, notes, and snippets.

@kontur
Last active August 29, 2015 14:19
Show Gist options
  • Save kontur/794b04537a9bea84c40c to your computer and use it in GitHub Desktop.
Save kontur/794b04537a9bea84c40c to your computer and use it in GitHub Desktop.
Arduino get direction / bearing from two geolocations
/*
* Arduino geolocation bearing calculation based on two geolocation latitude-longitude values
* Johannes 'kontur' Neumeier, 2015
* https://gist.github.com/kontur/794b04537a9bea84c40c
*/
void setup() {
Serial.begin(9600);
Serial.println(getDirection(60.1650338, 24.8768908, 60.1243045, 26.2730065));
}
void loop() {
}
/*
reference java implementation
protected static double bearing(double lat1, double lon1, double lat2, double lon2){
double longitude1 = lon1;
double longitude2 = lon2;
double latitude1 = Math.toRadians(lat1);
double latitude2 = Math.toRadians(lat2);
double longDiff= Math.toRadians(longitude2-longitude1);
double y= Math.sin(longDiff)*Math.cos(latitude2);
double x=Math.cos(latitude1)*Math.sin(latitude2)-Math.sin(latitude1)*Math.cos(latitude2)*Math.cos(longDiff);
return (Math.toDegrees(Math.atan2(y, x))+360)%360;
}
*/
int getDirection(float latitude1, float longitude1, float latitude2, float longitude2) {
float lat1 = toRadians(latitude1);
float lat2 = toRadians(latitude2);
float lng1 = toRadians(longitude1);
float lng2 = toRadians(longitude2);
float Y = sin(lng2 - lng1) * cos(lat2);
float X = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(lng2 - lng1);
float deg = toDegrees(atan2(Y, X));
// note that this implementation doesn't use the module, but angles lower than 0 get augmented by 360 only
if (deg < 0) {
deg = 360 + deg;
}
float angle = deg;
int a = (int) (abs(angle) + (1 / 7200));
return a;
}
float toRadians(float angle) {
return (PI / 180) * angle;
}
float toDegrees(float rad) {
return (rad * 180) / PI;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment