Adafruit Ultimate GPS Logger Shield

The Adafruit Ultimate GPS Logger Shield is a great product, and Adafruit provides a very good tutorial to get started.   When it came to actually doing something with the GPS coordinates, I ran into a few challenges.   The code below provides subroutines and functions to convert GPS coordinates into values that can be used.  

See my project Transmitting GPS data across CAN bus on how to convert GPS coordinates into a single CAN bus message.  


#include "math.h"       /* modf */

void setup() {

// Extracting GPS coordinates into useful values..
if (GPS.fix) {
  Serial.print("Location: ");
  Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
  Serial.print(", "); 
  Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
  //Location: 4026.4343N, 7607.3623W
  
  Serial.print("Lat in decimal degrees: ");
  printFloat(gpsGetDecimalDegFromUltGPS_LatLong(GPS.latitude, GPS.lat), 4);
  Serial.println("  ");
  // 40.4478

  Serial.print("Long in decimal degrees: ");
  printFloat(gpsGetDecimalDegFromUltGPS_LatLong(GPS.longitude, GPS.lon), 4);
  Serial.println("  ");
  // -76.1287
  
}


..
}


///////////////////////////////////////////////////////////////////////////
// gps functions

float gpsGetDecimalDegFromUltGPS_LatLong(float in_coords, char NSEW) {
  // Convert the latitude or longitude float value from the
  // Ultimate GPS (GPS.latitude or GPS.longitude) to GPS
  // decimal degrees format.
  // For the location: 4026.4370N, 7607.3613W
  // in_coords holds the lat or long (4026.437 or 7607.3613).
  // NSEW hold the lat or long direction North, South, East, West (NSEW)
  // N & E are positive, S & W are negative
  // Lat values vary from 90° N to 90° S.
  // Long values vary from 180° W to 180° E.
  
  // Get the first two digits by turning f into an integer, then doing an integer divide by 100;
  // firsttowdigits should be 77 at this point.
  int firsttwodigits = ((int)in_coords)/100;                               //This assumes that f < 10000.
  float nexttwodigits = in_coords - (float)(firsttwodigits*100);
  
  int left_part = intOfFloat(in_coords);
  int right_part = fractionOfFloat(in_coords, 4, left_part);
  float fRightPart = (float)right_part / 10000.0;
  float theFinalAnswer = (float)(firsttwodigits + (nexttwodigits + fRightPart)/60.0);

  if (NSEW == 'S' || NSEW == 'W') {
    // S & E are negative
    theFinalAnswer = theFinalAnswer * (-1.0);
  }
 
  return theFinalAnswer;
}

int intOfFloat(float f) {
  // intOfFloat(4026.4370) = 4026
  int left_part;
  left_part = floor(f);
  return left_part;
}

int fractionOfFloat(float f, byte numDecPlaces, int left_part) {
  // fractionOfFloat(4026.4370, 4, 4026) = 4370
  int right_part;
  right_part = f * pow(10, numDecPlaces) - left_part * pow(10, numDecPlaces);
  return right_part;
}

///////////////////////////////////////////////////////////////////////////
void printFloat(float value, int places) {
  // printFloat prints out the float 'value' rounded to 'places' places after the decimal point
  // Follow with println as needed.
  
  // this is used to cast digits
  int digit;
  float tens = 0.1;
  int tenscount = 0;
  int i;
  float tempfloat = value;

  // make sure we round properly. this could use pow from , but doesn't seem worth the import
  // if this rounding step isn't here, the value  54.321 prints as 54.3209

  // calculate rounding term d:   0.5/pow(10,places)  
  float d = 0.5;
  if (value < 0)
    d *= -1.0;
  // divide by ten for each decimal place
  for (i = 0; i < places; i++)
    d/= 10.0;    
  // this small addition, combined with truncation will round our values properly
  tempfloat +=  d;

  // first get value tens to be the large power of ten less than value
  // tenscount isn't necessary but it would be useful if you wanted to know after this how many chars the number will take

  if (value < 0)
    tempfloat *= -1.0;
  while ((tens * 10.0) <= tempfloat) {
    tens *= 10.0;
    tenscount += 1;
  }

  // write out the negative if needed
  if (value < 0)
    Serial.print('-');

  if (tenscount == 0)
    Serial.print(0, DEC);

  for (i=0; i< tenscount; i++) {
    digit = (int) (tempfloat/tens);
    Serial.print(digit, DEC);
    tempfloat = tempfloat - ((float)digit * tens);
    tens /= 10.0;
  }

  // if no places after decimal, stop now and return
  if (places <= 0)
    return;

  // otherwise, write the point and continue on
  Serial.print('.');  

  // now write out each decimal place by shifting digits one by one into the ones place and writing the truncated value
  for (i = 0; i < places; i++) {
    tempfloat *= 10.0;
    digit = (int) tempfloat;
    Serial.print(digit,DEC);  
    // once written, subtract off that digit
    tempfloat = tempfloat - (float) digit;
  }
  
}

byte countDigits(int num){
  byte count=0;
  while(num){
  num=num/10;
  count++;
  }
  return count;
}

int getDigitRightToLeft(unsigned int number, int digit) {
  // gets the digit specified, counting from the left of the
  // decimal point and moving to the left.
  for (int i=0; i>8) & 0xff;
  return lsb;
}

void updateCanMsgFromGPS_LatLong(float GPSlat, float GPSlong) {

  int msgStartBit = 0;
  int msgLength = 16;
  float msgFactor = 1.0;
  int msgOffset = -90;
  int numDecPlaces = 4;
 
  // clear out msg[]
  for (int i=0; i<8; i++) {
    CANmsg[i] = 0;
  }

  /////////////////////////////////////////////////////////////
  // Latitude
  
  double intpart, fractpart;
  fractpart = modf(GPSlat, &intpart);
  int left_part = (int) intpart;
  float right_part = abs((float) fractpart);

  // updateCanMsgFromFloat(float floatVal, int startBit, int msgLen, int offset, float factor) 
  updateCanMsgFromFloat(left_part, msgStartBit, msgLength, msgOffset, msgFactor);

  //Setup the right_part
  msgStartBit = 16;
  msgLength = 16;
  msgOffset = 0;
  msgFactor = 0.0001;
  // updateCanMsgFromFloat(float floatVal, int startBit, int msgLen, int offset, float factor) 
  updateCanMsgFromFloat(right_part, msgStartBit, msgLength, msgOffset, msgFactor);

  /////////////////////////////////////////////////////////////
  // Longitude
  fractpart = modf(GPSlong, &intpart);
  left_part = (int) intpart;
  right_part = abs((float) fractpart);

  //Setup the left_part
  msgStartBit = 32;
  msgLength = 16;
  msgOffset = -180;
  msgFactor = 1.0;
  // updateCanMsgFromFloat(float floatVal, int startBit, int msgLen, int offset, float factor) 
  updateCanMsgFromFloat(left_part, msgStartBit, msgLength, msgOffset, msgFactor);

  //Setup the right_part
  msgStartBit = 48;
  msgLength = 16;
  msgOffset = 0;
  msgFactor = 0.0001;
  // updateCanMsgFromFloat(float floatVal, int startBit, int msgLen, int offset, float factor) 
  updateCanMsgFromFloat(right_part, msgStartBit, msgLength, msgOffset, msgFactor);
}

 

Arduino Uno Code

Here is code to help parse the GPS information from output of the Adafruit Ultimate GPS Logger Shield.  

/*
  Adafruit Ultimate GPS Logger Shield
  
  Uno / Duemilanove / Diecemila / (SoftSerial different for Leonardo)
    
  Parse GPS information .
  
  Resources:
    DIO7    SoftwareSerial  GPS
    DIO8    SoftwareSerial  GPS
    DIO10   SD card         CS
    DIO13   LED
    
    Note that tests indicate you may be able to use DIO10.
    DIO 2 to 6 and 9 may be used without any effect on the GPS.  

*/


// Test code for Adafruit GPS modules using MTK3329/MTK3339 driver
//
// This code shows how to listen to the GPS module in an interrupt
// which allows the program to have more 'freedom' - just parse
// when a new NMEA sentence is available! Then access data when
// desired.
//
// Tested and works great with the Adafruit Ultimate GPS module
// using MTK33x9 chipset
//    ------> http://www.adafruit.com/products/746
// Pick one up today at the Adafruit electronics shop 
// and help support open source hardware & software! -ada

//This code is intended for use with Arduino Leonardo and other ATmega32U4-based Arduinos

#include 
#include 

// Connect the GPS Power pin to 5V
// Connect the GPS Ground pin to ground
// If using software serial (sketch example default):
//   Connect the GPS TX (transmit) pin to Digital 8
//   Connect the GPS RX (receive) pin to Digital 7
// If using hardware serial:
//   Connect the GPS TX (transmit) pin to Arduino RX1 (Digital 0)
//   Connect the GPS RX (receive) pin to matching TX1 (Digital 1)

// If using software serial, keep these lines enabled
// (you can change the pin numbers to match your wiring):
SoftwareSerial mySerial(8, 7);
Adafruit_GPS GPS(&mySerial);

// If using hardware serial, comment
// out the above two lines and enable these two lines instead:
//Adafruit_GPS GPS(&Serial1);
//HardwareSerial mySerial = Serial1;

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences
// MK do not change to false. Need this.
#define GPSECHO  true

/////////////////////////////////////////////////////////////////////////
byte pinLED13 = 13;
/////////////////////////////////////////////////////////////////////////

// set 'true' to see all details, false for the parsed GPS data only
#define DEBUG false

void setup()  
{
    
  // connect at 115200 so we can read the GPS fast enough and echo without dropping chars
  // also spit it out
  Serial.begin(115200);
  delay(5000);
  Serial.println("Adafruit GPS library basic test!");

  // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
  GPS.begin(9600);
  
  // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  // uncomment this line to turn on only the "minimum recommended" data
  //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
  // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since
  // the parser doesn't care about other sentences at this time
  
  // Set the update rate
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate
  // For the parsing code to work nicely and have time to sort thru the data, and
  // print it out we don't suggest using anything higher than 1 Hz

  // Request updates on antenna status, comment out to keep quiet
  GPS.sendCommand(PGCMD_ANTENNA);

  pinMode(pinLED13, OUTPUT);
  delay(1);
  blinkLED13();
  
  delay(1000);
  // Ask for firmware version
  mySerial.println(PMTK_Q_RELEASE);
}

uint32_t timer = millis();
void loop() {
  char c = GPS.read();
  // if you want to debug, this is a good time to do it!
  if ((c) && (GPSECHO))
    #if DEBUG
      Serial.write(c); 
    #endif
  // if a sentence is received, we can check the checksum, parse it...
  if (GPS.newNMEAreceived()) {
    // a tricky thing here is if we print the NMEA sentence, or data
    // we end up not listening and catching other sentences! 
    // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false
  
    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

  // if millis() or timer wraps around, we'll just reset it
  if (timer > millis())  timer = millis();
  // approximately every 2 seconds or so, print out the current stats
  if (millis() - timer > 5000) { 
    timer = millis(); // reset the timer
    
    Serial.print("\nUTC Time: ");
    Serial.print(GPS.hour, DEC); Serial.print(':');
    Serial.print(GPS.minute, DEC); Serial.print(':');
    Serial.print(GPS.seconds, DEC); Serial.print('.');
    Serial.println(GPS.milliseconds);
    //Time: 13:6:37.0

    Serial.print("UTC Date: ");
    Serial.print(GPS.day, DEC); Serial.print('/');
    Serial.print(GPS.month, DEC); Serial.print("/20");
    Serial.println(GPS.year, DEC);
    //Date: 3/8/2014
    
    Serial.print("Fix: "); Serial.print((int)GPS.fix);
    Serial.print(" quality: "); Serial.println((int)GPS.fixquality); 
    //Fix: 1 quality: 2

    if (GPS.fix) {
      Serial.print("Location: ");
      Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
      Serial.print(", "); 
      Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
      //Location: 4026.4343N, 7607.3623W
      
      Serial.print("Lat in decimal degrees: ");
      printFloat(gpsGetDecimalDegFromUltGPS_LatLong(GPS.latitude, GPS.lat), 4);
      Serial.println("  ");
      // 40.4478

      Serial.print("Long in decimal degrees: ");
      printFloat(gpsGetDecimalDegFromUltGPS_LatLong(GPS.longitude, GPS.lon), 4);
      Serial.println("  ");
      // -76.1287
      
      Serial.print("Speed (knots): "); Serial.println(GPS.speed);
      //Speed (knots): 0.31

      Serial.print("Angle: "); Serial.println(GPS.angle);
      //Angle: 59.69
      
      Serial.print("Altitude: "); Serial.println(GPS.altitude);
      //Altitude: 109.70

      Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
      //Satellites: 8
    }
    Serial.println("  ");
  }
  
  
}

///////////////////////////////////////////////////////////////////////////
// gps functions

float gpsGetDecimalDegFromUltGPS_LatLong(float in_coords, char NSEW) {
  // Convert the latitude or longitude float value from the
  // Ultimate GPS (GPS.latitude or GPS.longitude) to GPS
  // decimal degrees format.
  // For the location: 4026.4370N, 7607.3613W
  // in_coords holds the lat or long (4026.437 or 7607.3613).
  // NSEW hold the lat or long direction North, South, East, West (NSEW)
  // N & E are positive, S & W are negative
  // Lat values vary from 90° N to 90° S.
  // Long values vary from 180° W to 180° E.
  
  // Get the first two digits by turning f into an integer, then doing an integer divide by 100;
  // firsttowdigits should be 77 at this point.
  int firsttwodigits = ((int)in_coords)/100;                               //This assumes that f < 10000.
  float nexttwodigits = in_coords - (float)(firsttwodigits*100);
  
  int left_part = intOfFloat(in_coords);
  int right_part = fractionOfFloat(in_coords, 4, left_part);
  float fRightPart = (float)right_part / 10000.0;
  float theFinalAnswer = (float)(firsttwodigits + (nexttwodigits + fRightPart)/60.0);

  if (NSEW == 'S' || NSEW == 'W') {
    // S & E are negative
    theFinalAnswer = theFinalAnswer * (-1.0);
  }
 
  return theFinalAnswer;
}

int intOfFloat(float f) {
  // intOfFloat(4026.4370) = 4026
  int left_part;
  left_part = floor(f);
  return left_part;
}

int fractionOfFloat(float f, byte numDecPlaces, int left_part) {
  // fractionOfFloat(4026.4370, 4, 4026) = 4370
  int right_part;
  right_part = f * pow(10, numDecPlaces) - left_part * pow(10, numDecPlaces);
  return right_part;
}

///////////////////////////////////////////////////////////////////////////
void printFloat(float value, int places) {
  // printFloat prints out the float 'value' rounded to 'places' places after the decimal point
  // Follow with println as needed.
  
  // this is used to cast digits
  int digit;
  float tens = 0.1;
  int tenscount = 0;
  int i;
  float tempfloat = value;

  // make sure we round properly. this could use pow from , but doesn't seem worth the import
  // if this rounding step isn't here, the value  54.321 prints as 54.3209

  // calculate rounding term d:   0.5/pow(10,places)  
  float d = 0.5;
  if (value < 0)
    d *= -1.0;
  // divide by ten for each decimal place
  for (i = 0; i < places; i++)
    d/= 10.0;    
  // this small addition, combined with truncation will round our values properly
  tempfloat +=  d;

  // first get value tens to be the large power of ten less than value
  // tenscount isn't necessary but it would be useful if you wanted to know after this how many chars the number will take

  if (value < 0)
    tempfloat *= -1.0;
  while ((tens * 10.0) <= tempfloat) {
    tens *= 10.0;
    tenscount += 1;
  }

  // write out the negative if needed
  if (value < 0)
    Serial.print('-');

  if (tenscount == 0)
    Serial.print(0, DEC);

  for (i=0; i< tenscount; i++) {
    digit = (int) (tempfloat/tens);
    Serial.print(digit, DEC);
    tempfloat = tempfloat - ((float)digit * tens);
    tens /= 10.0;
  }

  // if no places after decimal, stop now and return
  if (places <= 0)
    return;

  // otherwise, write the point and continue on
  Serial.print('.');  

  // now write out each decimal place by shifting digits one by one into the ones place and writing the truncated value
  for (i = 0; i < places; i++) {
    tempfloat *= 10.0;
    digit = (int) tempfloat;
    Serial.print(digit,DEC);  
    // once written, subtract off that digit
    tempfloat = tempfloat - (float) digit;
  }
  
}

byte countDigits(int num){
  byte count=0;
  while(num){
  num=num/10;
  count++;
  }
  return count;
}

int getDigitRightToLeft(unsigned int number, int digit) {
  // gets the digit specified, counting from the left of the
  // decimal point and moving to the left.
  for (int i=0; i 0; i--){
    digitalWrite(pinLED13, HIGH);
    delay(1);
    digitalWrite(pinLED13, LOW);
    delay(25);
  }    
}

 


Do you need help developing or customizing a IoT product for your needs?   Send me an email requesting a free one hour phone / web share consultation.  

 

The information presented on this website is for the author's use only.   Use of this information by anyone other than the author is offered as guidelines and non-professional advice only.   No liability is assumed by the author or this web site.