GPS position and speed (NEO-6M)
Parse NMEA sentences from a NEO-6M GPS with TinyGPSPlus and print position, speed, altitude and UTC time.
Communication · Beginner
In a real product: Vehicle fleet tracker (Rail and transport): Reports each vehicle's position and speed from GPS.
A GPS module does the hard part, the satellite maths, and sends the answer as plain text lines called NMEA sentences. The sketch's job is to read that serial stream and pull the numbers out of it.
What you'll learn
- Reading a serial device with SoftwareSerial while Serial stays free for the monitor
- What NMEA sentences look like, and why each ends with a checksum
- Feeding a parser byte by byte instead of waiting for whole lines
How it works
Once a second the NEO-6M sends a burst of sentences at 9600 baud, such as $GPRMC,083002.00,A,1258.29600,N,07735.67600,E,...*7E: UTC time, A for a valid fix, latitude and longitude in degrees and minutes, speed and date. The two hex digits after * are the XOR of every character between $ and *, so a corrupted sentence is thrown away.
gps.encode() takes one character at a time and returns once a sentence completes. Reading every available byte on each pass of loop() keeps SoftwareSerial's small buffer from overflowing.
Try this
- Click the module while it runs and change the latitude, longitude or speed.
- Set fix to 0: the sentences arrive with empty position fields and
location.isValid()turns false. - Compute the distance to a fixed point with
TinyGPSPlus::distanceBetween().
sketch.ino
// A NEO-6M GPS on SoftwareSerial (its TX to pin 4) parsed with TinyGPSPlus; prints a summary every second.
#include <SoftwareSerial.h>
#include <TinyGPSPlus.h>
SoftwareSerial gpsSerial(4, 3); // RX, TX
TinyGPSPlus gps;
unsigned long lastPrint = 0;
void setup() {
Serial.begin(9600);
gpsSerial.begin(9600);
}
void loop() {
while (gpsSerial.available()) gps.encode(gpsSerial.read());
if (millis() - lastPrint < 1000) return;
lastPrint = millis();
if (!gps.location.isValid()) {
Serial.print("Waiting for a fix, satellites: ");
Serial.println(gps.satellites.value());
return;
}
Serial.print(gps.location.lat(), 5);
Serial.print(", ");
Serial.print(gps.location.lng(), 5);
Serial.print(" ");
Serial.print(gps.speed.kmph(), 1);
Serial.print(" km/h alt ");
Serial.print(gps.altitude.meters(), 0);
Serial.print(" m ");
char time[16];
snprintf(time, sizeof time, "%02d:%02d:%02d UTC", gps.time.hour(), gps.time.minute(), gps.time.second());
Serial.println(time);
}