3

I am trying to calculate the bearing just like in this example: Calculate bearing between two decimal GPS coordinates , but my environment is Arduino.

I got the code translated (please see below), but I am having issues with the floating points. I need a higher resolution/precision.

Using these points:

double r1 = 9.935483816921979;
double r2 = -84.05334153306967;
double g1 = 9.936029735119176;
double g2 = -84.0532617256946;

I get these results:

8.194077303640654 // In the js code from the example
9.229920 // from my Arduino code

How can I get more precision?

// Here is my Arduino Code
double getBearing(double lat1,double lng1,double lat2,double lng2) {
  lat1 = radians(lat1);
  lng1 = radians(lng1);
  lat2 = radians(lat2);
  lng2 = radians(lng2);

  double dLng = lng2 - lng1;
  double dPhi = log(tan(lat2 / 2.0 + PI / 4.0) / tan(lat1 / 2.0 + PI / 4.0));

  if (abs(dLng) > PI){
    if (dLng > 0.0)
     dLng = -(2.0 * PI - dLng);
  else
    dLng = (2.0 * PI + dLng);
  }

  return fmod((degrees(atan2(dLng, dPhi)) + 360.0), 360.0); 
}
2

You can calculate your bearing with this function.

float bearing(float lat,float lon,float lat2,float lon2){

    float teta1 = radians(lat);
    float teta2 = radians(lat2);
    float delta1 = radians(lat2-lat);
    float delta2 = radians(lon2-lon);

    //==================Heading Formula Calculation================//

    float y = sin(delta2) * cos(teta2);
    float x = cos(teta1)*sin(teta2) - sin(teta1)*cos(teta2)*cos(delta2);
    float brng = atan2(y,x);
    brng = degrees(brng);// radians to degrees
    brng = ( ((int)brng + 360) % 360 ); 

    Serial.print("Heading GPS: ");
    Serial.println(brng);

    return brng;


  }

where variables are:

  • lat = your current gps latitude.
  • lon = your current gps longitude.
  • lat2 = your destiny gps latitude.
  • lon2 = your destiny gps longitude.
  • You never use 'delta1' in the formula, is that intentional or a mistake? – fiend Mar 15 at 12:52
  • delta1 is used in the distance not in the bearing ..... – Mario Alzate Apr 6 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.