To modify the code so that it logs the GPS location every 5 seconds, you can introduce a simple time delay in the loop. Modify the previous code by adding a timing mechanism to ensure that GPS data is read, and the location is logged every 5 seconds. Here's how you can adjust it:
Modified Arduino Code
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
// Choose two pins for the GPS serial communication
static const int RXPin = 3, TXPin = 1;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
// Variable to store the last logging time
unsigned long lastLogTime = 0;
void setup() {
// Start serial communication for console output
Serial.begin(115200);
// Start serial communication with the GPS module
ss.begin(GPSBaud);
Serial.println("ESP8266 & NEO-6M GPS Module Example");
}
void loop() {
// This sketch displays information once every 5 seconds
while (ss.available() > 0) {
gps.encode(ss.read());
// Check if 5 seconds have passed since the last log
if (millis() - lastLogTime >= 5000) {
if (gps.location.isValid()) {
Serial.print("Latitude: ");
Serial.print(gps.location.lat(), 6);
Serial.print(", Longitude: ");
Serial.print(gps.location.lng(), 6);
Serial.print(", Altitude: ");
Serial.print(gps.altitude.meters());
Serial.println("m");
// Update the last log time
lastLogTime = millis();
} else {
Serial.println("Waiting for valid GPS signal...");
}
}
}
}
Explanation:
- A
lastLogTime variable is used to keep track of the last time the GPS coordinates were logged.
- The
millis() function provides the current time since the Arduino started in milliseconds.
- The code checks if 5000 milliseconds (5 seconds) have passed since
lastLogTime. If true, and if valid GPS data is available, it logs the GPS coordinates.
gps.location.isValid() checks if the GPS data received is valid, which ensures location accuracy before logging.
Steps to Run the Modified Code:
- Install the TinyGPS++ library from the Arduino Library Manager, if not already done.
- Connect the hardware as per the connection instructions in the first response.
- Upload the modified code to the NodeMCU using the Arduino IDE.
- Open the Serial Monitor to see the output. Ensure that the baud rate is set to 115200.
Notes:
- Ensure the GPS module is in a position with a clear view of the sky to get a strong and valid signal.
- The GPS module may take some time to get a satellite fix, particularly after it has been powered off or moved to a new location.