#include <SoftwareSerial.h>
#include <TinyGPS++.h>
#include <SD.h>
#define GPS_TX 2 // TX pin of GPS module connected to Arduino's RX pin
#define GPS_RX 3 // RX pin of GPS module connected to Arduino's TX pin
#define SD_CS 10 // Chip select pin of SD module
#define SD_CD 9 // Card detect pin of SD module
SoftwareSerial gpsSerial(GPS_TX, GPS_RX);
TinyGPSPlus gps;
File gpsFile;
void setup() {
Serial.begin(9600);
gpsSerial.begin(9600);
pinMode(SD_CD, INPUT_PULLUP); // Set SD card detect pin as input with internal pull-up resistor
if (!SD.begin(SD_CS)) {
Serial.println("Failed to initialize SD card!");
return;
}
gpsFile = SD.open("gps_data.txt", FILE_WRITE);
if (!gpsFile) {
Serial.println("Failed to open file!");
return;
}
gpsFile.println("Latitude,Longitude");
}
void loop() {
while (gpsSerial.available() > 0) {
if (gps.encode(gpsSerial.read())) {
if (gps.location.isValid()) {
Serial.print("Latitude= ");
Serial.print(gps.location.lat(), 6);
Serial.print(" Longitude= ");
Serial.println(gps.location.lng(), 6);
gpsFile.print(gps.location.lat(), 6);
gpsFile.print(",");
gpsFile.println(gps.location.lng(), 6);
} else {
Serial.println("Location not available");
}
}
}
// Check if SD card is inserted
if (digitalRead(SD_CD) == LOW) {
Serial.println("SD card detected!");
} else {
Serial.println("SD card not detected!");
}
delay(1000); // Delay for stability
}