GPS correct delay implementation

Hey,

I connected the NEO-6M GPS module to an Arduino MKR NB 1500. When using the code below without a delay the altitude and number of satellites are printed correctly. However, when i insert a 2s delay the altitude and number of sattelites prints out 0 (see picture below). Can anyone tell me what i am doing wrong? Lat and Long values are blacked out for private reasons.

#include "TinyGPS++.h"
TinyGPSPlus gps;
#define gpsSerial Serial1


void setup() {
  // initialize serial communications
  Serial.begin(9600);
  gpsSerial.begin( 9600 );

}

void loop() {

  while ( gpsSerial.available() > 0)
  {
    gps.encode(gpsSerial.read());
    }

  if (gps.location.isValid())
  {
    Serial.print("LAT=");  Serial.println(gps.location.lat(), 6);
    Serial.print("LONG="); Serial.println(gps.location.lng(), 6);
    Serial.print("ALT=");  Serial.println(gps.altitude.meters());
    Serial.print("# of satallites="); Serial.println(gps.satellites.value());
    delay(2000);
    }
}

Thanks in Advance

when you add a delay, you stop feeding the beast

gps.encode(gpsSerial.read());

the Serial buffer is small and at 9600 bauds, you get 960 characters per second... so you have now missed 1920 characters from the GPS and only have the last 64 in the buffer...

use millis() to drive your display only from time to time.

#include "TinyGPS++.h"
TinyGPSPlus gps;
#define gpsSerial Serial1
unsigned long lastDisplayTime = 0;

void setup() {
  Serial.begin(9600);
  gpsSerial.begin(9600);
}

void loop() {
  while ( gpsSerial.available() > 0)gps.encode(gpsSerial.read());

  if (gps.location.isValid() && (millis() - lastDisplayTime >= 2000)) {
    Serial.print("LAT=");  Serial.println(gps.location.lat(), 6);
    Serial.print("LONG="); Serial.println(gps.location.lng(), 6);
    Serial.print("ALT=");  Serial.println(gps.altitude.meters());
    Serial.print("# of satallites="); Serial.println(gps.satellites.value());
    lastDisplayTime = millis();
  }
}
2 Likes

Thank you so much Jackson for a clear explanation and answer to my question. U forgot the brackets in the while loop, but the code is working perfectly now!

I did not forget anything as my while loop had only 1 statement, so I did not need the brackets to make a compound statement... :wink:

but it's fine to add them and write

  while (gpsSerial.available() > 0) {
    gps.encode(gpsSerial.read());
  }

it does not change anything... (it's a good practice for some to add the brackets always)

PS: it's important to understand what are the different statement is in C++, will make your life much easier

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.