/**
*Gets input from GPS
*/
#include <NewSoftSerial.h>
//NewSoftSerial(in, out, inverted)
NewSoftSerial myGPS(2, 3, true); //for I/O from the GPS without interfering with Serial I/O
String s = ""; //For containing input from myGPS
//converts doubles to Strings, used in Longitude and Latitude parsing
String doubleToString(double d) {
String s = (int)d;
d = d - (int)d;
while(d != (int)d)
d = d * 10;
s += String(".") + (int)d;
return s;
}
int count(String str, String toCount) {
if (str.indexOf(toCount) < 0)
return 0;
int count = 0;
for (int i = 0; i < str.length();) {
if (str.substring(i, i+toCount.length()).equals(toCount)) {
count = count + 1;
i = i + toCount.length();
} else
i = i + 1;
}
return count;
}
//Splits String by a regex, needed for separating parts of $GPGGA
String* split(String str, String toSplit) {
String strs[count(str,toSplit)+1];
int i = 0;
for(;str.indexOf(toSplit) >= 0;) {
strs[i] = str.substring(0,str.indexOf(toSplit));
str = str.substring(str.indexOf(toSplit) + toSplit.length());
i = i + 1;
}
strs[i] = str;
return strs;
}
//Parses an hhmmss.ss
void parseTime(String time) {
Serial.print("Time: ");
Serial.print(time.substring(0,2));
Serial.print(":");
Serial.print(time.substring(2,4));
Serial.print(":");
Serial.print(time.substring(4));
}
//Parse a ddmm.mmmm
String parseLat(String latitude) {
if (latitude.length() == 0)
return "Unknown";
String str = latitude.substring(0,2) + "d " + latitude.substring(2,4).toInt() + "' ";
if (5 < latitude.length()) {
String sub = latitude.substring(5);
double seconds = static_cast<double>(sub.toInt());
double tenths = 1;
for (int i = 0; i < sub.length(); i = i + 1)
tenths = tenths * 10;
seconds = seconds / tenths;
seconds = seconds * 60;
str += doubleToString(seconds) + "\"";
}
return str;
}
//Parses a dddmm.mmm
String parseLong(String longitude) {
if (longitude.length() == 0)
return "Unknown";
String str = longitude.substring(0,3) + "d " + longitude.substring(3,5).toInt() + "' ";
if (6 < longitude.length()) {
String sub = longitude.substring(6);
double seconds = static_cast<double>(sub.toInt());
double tenths = 1;
for (int i = 0; i < sub.length(); i = i + 1)
tenths = tenths * 10;
seconds = seconds / tenths;
seconds = seconds * 60;
str += doubleToString(seconds) + "\"";
}
return str;
}
//Parses the $GPGGA for output
void parseGPGGA(String gpgga) {
if (!gpgga.startsWith("$GPGGA"))
return;
String* strs = split(gpgga, ",");
int sz = count(gpgga,",");
for (int i = 0; i <= sz; i = i + 1) {
Serial.print(strs[i]);
Serial.print(",");
}
//parseTime(strs[1]);
Serial.println();
}
//Set up serial ports
void setup() {
myGPS.begin(4800);
Serial.begin(115200);
}
//Get information and maybe output it
void loop() {
if (myGPS.available()) {
s += (char)myGPS.read();
}
if (s.endsWith("\n")) {
if (s.substring(0,6).equalsIgnoreCase("$GPGGA")) {
Serial.print(s);
parseGPGGA(s);
}
s = "";
}
}