This is the modified example sketch from the TinyGPS library. It samples the serial data from the GPS once a minute and if that data is valid it writes it to the SD card.
#include <TinyGPS.h>
#include <SD.h>
#include <SPI.h>
TinyGPS gps; //create an instance of the GPS
int sd = 7; //chip select for SD card
//Array of data used to reconfigure GPS to send updates at 0.016 hz
const uint8_t gps_config_change[35] PROGMEM = {
0xB5, 0x62, 0x06, 0x08, 0x06, 0x00, 0x60, //Set update to 0.016 hz (1 time every minute)
0xEA, 0x01, 0x00, 0x01, 0x00, 0x60, 0x8C,
0xB5, 0x62, 0x06, 0x09, 0x0D, 0x00, 0x00, //Save config
0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x1D, 0xAB
};
void setup()
{
Serial.begin(38400); //Begin serial connection with GPS module
//Serial.write(gps_config_change, sizeof(gps_config_change)); //Write config to GPS
pinMode(sd, OUTPUT); //Set cs pin for SD card as output
if (!SD.begin(sd)) //If SD card is corrupt or disconnected, exit the program
{
return;
}
}
void loop()
{
updateData(); //Update variables with new GPS data and write to SD card
}
void updateData() //Read data from the GPS every 60s (once a minute)
{
bool newData = false;
for (unsigned long start = millis(); millis() - start < 60000;) {
while (Serial.available())
{
char c = Serial.read();
if (gps.encode(c)) //If there is new valid data from the GPS, then newData = true
newData = true;
}
}
if (newData)
{
float flat, flon, alt; //Location variables for log file
unsigned long age; //time variable for log file
gps.f_get_position(&flat, &flon, &age); //update the location (only lat, lon) and time
File dataFile = SD.open("LOG.txt", FILE_WRITE); //Open the log file for writing
if (dataFile) //If the file was successfully opened, write new data to it
{
int year;
byte month, day, hour, minute, second, hundredths;
unsigned long age;
gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age); //store age into separate fields
if (age != TinyGPS::GPS_INVALID_AGE) //format and store date and time in file
{
char sz[32];
sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
month, day, year, hour, minute, second);
dataFile.print(sz);
}
dataFile.print(",");
dataFile.print(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6); //store latitude
dataFile.print(",");
dataFile.print(flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6); //store longitude
dataFile.print(",");
alt = gps.f_altitude(); //get the altitude
dataFile.println(alt == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : alt, 6); //store altitude
dataFile.close(); //close the log file
}
}
}