#include <TinyGPS++.h>
#include <WiFi.h>
#include <HTTPClient.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace with your ThingsBoard server and device token
const char* thingboardURL = "https://demo.thingsboard.io/api/v1/Rf7HY24EinhL44wERGDf/telemetry";
// Initialize the TinyGPS++ object
TinyGPSPlus gps;
// Initialize the hardware serial port for GPS module
HardwareSerial gpsSerial(1);
void setup() {
// Start the serial communication for debugging
Serial.begin(115200);
// Start the hardware serial communication for GPS module
gpsSerial.begin(9600, SERIAL_8N1, 16, 17); // RX: GPIO16, TX: GPIO17
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
// Check if data is available from the GPS module
while (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
}
// If a valid GPS location is available, send it to ThingsBoard
if (gps.location.isUpdated()) {
float latitude = gps.location.lat();
float longitude = gps.location.lng();
float altitude = gps.altitude.meters();
int satellites = gps.satellites.value();
int hdop = gps.hdop.value();
// Prepare JSON payload
String payload = "{";
payload += "\"latitude\":" + String(latitude, 6) + ",";
payload += "\"longitude\":" + String(longitude, 6) + ",";
payload += "\"altitude\":" + String(altitude) + ",";
payload += "\"satellites\":" + String(satellites) + ",";
payload += "\"hdop\":" + String(hdop);
payload += "}";
// Send data to ThingsBoard
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(thingboardURL); // Use the correct URL
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
// Print GPS data to Serial Monitor
Serial.print("Latitude: ");
Serial.println(latitude, 6);
Serial.print("Longitude: ");
Serial.println(longitude, 6);
Serial.print("Altitude: ");
Serial.println(altitude);
Serial.print("Satellites: ");
Serial.println(satellites);
Serial.print("HDOP: ");
Serial.println(hdop);
// Delay before next reading
delay(100); // Delay for 5 seconds
}
}