CHAPTER 9 ■ IOT PATTERNS: LOCATION AWARE
TinyGPS library. This library parses data coming from the GPS module and provides an
easy way to retrieve the required information. So initialize a variable of the TinyGPS library.
The getGPSCoordinates() function reads the GPS data from serial ports D2 and
D3. The GPS module might take a few seconds to find a satellite, so the latitude and
longitude values returned might not be valid. If latitude and longitude are equal to
TinyGPS::GPS_INVALID_F_ANGLE , that means the coordinates are invalid, so until the
code receives valid coordinates, it keeps printing Searching for Satellite on the serial
monitor. Once the valid coordinates are received, the transmitSensorData(latitude,
longitude) function is called.
Listing 9-6. Code for Reading GPS Coordinates
TinyGPS gps;
SoftwareSerial ss(2, 3); // GPS TX = Arduino D2, GPS RX = Arduino D3
static void smartdelay(unsigned long ms)
{
unsigned long start = millis();
do
{
while (ss.available())
gps.encode(ss.read());
} while (millis() - start < ms);
}
void getGPSCoordinates()
{
float latitude;
float longitude;
unsigned long age = 0;
gps.f_get_position(&latitude, &longitude, &age);
smartdelay(10000);
// Transmit sensor data
if(latitude != TinyGPS::GPS_INVALID_F_ANGLE &&
longitude != TinyGPS::GPS_INVALID_F_ANGLE)
{
transmitSensorData(latitude, longitude);
}
else
{
Serial.println("[INFO] Searching for Satellite");
}
}