Using adafruit GPS library within larger code

I am using an adafruit ultimate GPS module. I have had this wired up and working and printing the data so I know it works. Now I am looking to use the code and put it into a larger project. To start simple I have simply tried to have the main loop which then calls another loop that reads the GPS and then converts it into a number of varibales which can be combined into a csv string that at a later date I can write to an SD card with data from other sensors. However, when using the code I have it is not getting the data from the GPS and putting it in my string when calling it in a different loop, I think that this is something to do with the timing of the GPS library however i dont understand the library properly so any help would be appreciated. Heres the code I have tried:

#include <SoftwareSerial.h>
#include <Adafruit_GPS.h>

#define GPSECHO  true

String datastring, h, m, s, D, M, Y, f, q, LAT, VERT, LON, HOR, S, A, ALT, SAT, title;
int hour;
int minute;
int seconds;
int day;
int month;
int year;
int fix;
int quality;
float Lat;
char NS;
float Lon;
char EW;
float Speed;
float Angle;
float Altitude;
int Satellites;

// 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
#define GPSECHO  true

void setup()  
  // connect at 115200 so we can read the GPS fast enough and echo without dropping chars
  // also spit it out

  // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
  // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
  // uncomment this line to turn on only the "minimum recommended" data
  // 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

  title = String("Hour, Minute, Secconds,  Day, Month, Year,  fix, quality,  Latitude, Longitude,  Speed, Angle,  Altitude,  Satellites");

void loop(){
  datastring = String(h + ',' + m + ',' + s + ',' + D + ',' + M + ',' + Y + ',' + f + ',' + q + ',' + LAT + VERT + ',' + LON + HOR + ',' + S + ',' + A + ',' + ALT + ',' + SAT);



uint32_t timer = millis();
void Read_GPS()                     // run over and over again
  char c =;
  // if you want to debug, this is a good time to do it!
  if ((c) && (GPSECHO))
  // 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 > 2000) { 
    timer = millis(); // reset the timer

   h = String(hour = GPS.hour);
   m = String(minute = GPS.minute);
   s = String(seconds = GPS.seconds);

   D = String(day =;
   M = String(month = GPS.month);
   Y = String(year = GPS.year);

   f = String(fix = GPS.fix);
   q = String(quality = GPS.fixquality);

   LAT = String(Lat = GPS.latitude);
   VERT = String(NS =;

   LON = String(Lon = GPS.longitude);
   HOR = String(EW = GPS.lon);

   S = String(Speed = GPS.speed);
   A = String(Angle = GPS.angle);
   ALT = String(Altitude = GPS.altitude);
   SAT = String(Satellites = GPS.satellites); 

Don't feel too bad, 'cause you are not the first to run into this problem. Many libraries and their examples, and I mean almost all of 'em, are not structured in a way that lets you do more than one thing in a sketch.

In your case, you are trying to Serial.print debug info (or echoed GPS data) and trying to SD.write and trying to read other sensors.

By themselves, the examples work fine. Throw them together and... shazbot. Here's a recent thread that is similar to what you're doing.

This comes up so often! Here's some diagrams to help explain the timing. First, lets look at how the incoming GPS data relates to reading and parsing it:


Note how loop calls, and when it has read all the chars that have been received up to that point, it returns. loop may get called lots of times while it's waiting for the chars to come in. Eventually, the whole sentence is received, newNMEAreceived returns true, and you can go parse the new data.

The problem is that if you try to do anything that takes "too long", won't get called. The incoming chars stack up in the input buffer until it's full. After that, the chars will be dropped:


The next sentence, a GPRMC, continues to come in while Serial.print and SD.write are doing their thing... and data gets lost. Waaah! ;)

Fortunately, there is a way to work around this. It turns out that the GPS device is sending a batch of sentences once every second, maybe 5 at a time. Most of that one-second interval is actually is a "quiet time" that is perfect for doing other things:


All you need to do is hold on to the GPS pieces (date, time, location, etc.) until the quiet time comes around. You'll need to do the same thing with the additional sensors: hold on to the temperature, acceleration, whatever, until the quiet time comes around.

When new sentences start coming in again, hold on to the new set of pieces until the next quiet time starts. That's it!

I imagine you will be having more questions about how to do this, so think about it for a bit and see what you can come up with. When you start adding other sensors, they may have their own quiet times that need to get coordinated with the GPS time. For example, if it takes some time to read an analog sample, you might be able to request the conversion so that it is completed by the time the quiet time comes along. This is what resource-constrained, embedded programming is all about: timing and coordination.

BTW, this library has a usingInterrupt flag that will process incoming chars in the background. This will avoid losing chars, but you still need to make sure that you have time to call GPS.parse before the next sentence arrives. Again, it is better to wait for the "quiet time" before you do anything that takes "too long". Have you tried this?

boolean usingInterrupt = true

There's an example for using an SD card, too. Have you tried the examples/shieldsd_log.ino?

Cheers, /dev

Edited to add: String bad! Holding onto ints or floats good! Write 'em when it's a good time (hint, hint):

logfile.print( Speed ); // no String needed
logfile.print( ',' );
logfile.print( minute );