This program reads a serial string from a GPS reader. It parses the sentence and returns latitude and longitude.
It’s also a simple example of how to read an ASCII-formatted, comma-delimited serial protocol.
/*
GPS NMEA 0183 reader
reads a GPS string in the NMEA 0183 format and returns lat/long.
For more on GPS and NMEA, see the NMEA FAQ:
http://vancouver-webpages.com/peter/nmeafaq.txt
by Tom Igoe
created 1 June 2006
*/
import processing.serial.*;
int linefeed = 10; // linefeed in ASCII
int carriageReturn = 13; // carriage return in ASCII
Serial myPort; // The serial port
int sensorValue = 0; // the value from the sensor
float latitude = 0.0; // the latitude reading in degrees
String northSouth; // north or south?
float longitude = 0.0; // the longitude reading in degrees
String eastWest; // east or west?
void setup() {
// List all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 4800);
// read bytes into a buffer until you get a linefeed (ASCII 13):
myPort.bufferUntil(carriageReturn);
}
void draw() {
// not doing anything here
}
/*
serialEvent method is run automatically by the Processing applet
whenever the buffer reaches the byte value set in the bufferUntil()
method in the setup():
*/
void serialEvent(Serial myPort) {
// read the serial buffer:
String myString = myPort.readStringUntil(linefeed);
// if you got any bytes other than the linefeed:
if (myString != null) {
// parse the string:
parseString(myString);
}
}
/*
parseString takes the string and looks for the $GPGLL header.
if it finds it, it splits the string into components at the commas,
and stores them in appropriate variables.
*/
void parseString(String serialString) {
// split the string at the commas
//and convert the sections into integers:
String items[] = (split(serialString, ','));
// if the first item in the sentence is our identifier, parse the rest:
if (items[0].equals("$GPGLL") == true) {
// move the items from the string into the variables:
latitude = float(items[1]);
northSouth = items[2];
longitude = float(items[3]);
eastWest = items[4];
println(latitude + northSouth + "," +longitude + eastWest);
}
}