# Arduino Code for GPS Data via Lora Node to MQTT Server

**URL:** <https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066>\
**Category:** Programming\
**Created:** [January 9, 2023, 5:54am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066 "2023-01-09T05:54:28Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 5:54am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/1 "2023-01-09T05:54:28Z")

</div>

Hello There, I am trying it hard to extract the GPS lat/long data from the lora receivered incoming string to publish it to MQTT server, but no idea what arduino code required to working out for this?

```cpp
// This sketch displays information every time a new sentence is correctly encoded.
            
  if (Serial2.available()) {            
    String incomming = Serial2.readString();
    Serial.println(incomming);
    double latitude;
    double longitude;
    Serial.println(" ********** Publish MQTT data");
char mqtt_payload[50] = "";
snprintf (mqtt_payload, 50, "m1=%lf;%lf", latitude, longitude);
Serial.print("Publish message: ");
Serial.println(mqtt_payload);
client.publish(pubTopic, mqtt_payload);
Serial.println("> MQTT data published");
Serial.println(" ********** End ");
Serial.println(" *****************************************************");

delay(writeInterval);// delay
} else {
Serial.println(F("INVALID"));
}
}

```

![gps_data_serial monitor_screenshot_1](https://europe1.discourse-cdn.com/arduino/original/4X/9/8/1/9812d727228bc913b71bceea9b461eb03569e046.png)

For any Arduino code adding/updating help will be greatly appreciated to make it work. Thanking you.

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 6:18am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/2 "2023-01-09T06:18:59Z")

</div>

have a look at [how-to-get-the-best-out-of-this-forum](https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum/679966)  
in particular what microcontroller are you using  
what Lora board are you using  
are you using LoRaWAN or Lora point-to-point communication  
upload a schematic of your wiring

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 6:58am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/3 "2023-01-09T06:58:48Z")

</div>

> [@horace](#):
>
> in particular what microcontroller are you using  
> what Lora board are you using  
> are you using LoRaWAN or Lora point-to-point communication  
> upload a schematic of your wiring

Hello @horace ! Thanks for your feedback.

**in particular what microcontroller are you using**  
I am using ESP-32S microcontroller.

**what Lora board are you using**  
I am using Reyax RYLR998 Lora Modules

**are you using LoRaWAN or Lora point-to-point communication**  
I am using Lora point-to-point communication

**upload a schematic of your wiring**

 ![GPS Lora Diagram](https://europe1.discourse-cdn.com/arduino/original/4X/6/0/0/600a8224931950ca36c505c8d5c6b72a366e9a08.jpeg)

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 7:14am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/4 "2023-01-09T07:14:52Z")

</div>

just confirm you are receiving the GPS location OK as follows  
 ![image](https://europe1.discourse-cdn.com/arduino/original/4X/0/a/8/0a8d10be19daed90d796066a16bfe8b95c7950b9.png)  
and need to parse it to extract the lat/log  
if so upload a sample of the received string as text (you can put dummy data in lat/long)

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 7:24am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/5 "2023-01-09T07:24:08Z")

</div>

Hello @horace !

Please have the received string as below:

+RCV=2,20,41.000583,21.134611|,-34,11

+RCV=2,20,41.000583,00+RCV=2,20,41.000580,21.134611|,-34,11

\*\*\*\*\*\*\*\*\*\* Publish MQTT data

Publish message: m1=0.000000;0.000000

> MQTT data published

\*\*\*\*\*\*\*\*\*\* End

* * *

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 7:37am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/6 "2023-01-09T07:37:25Z")

</div>

assuming the format of the received data is consistent try using the string tokeniser, e.g.

```cpp
// strtok example - parse tokens

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  char str[] = "+RCV=2,20,41.000583,21.134611|,-34,11";
  char* pch; // pointer to tokens
  Serial.print("Splitting string ");
  Serial.print(str);
  Serial.println(" into tokens:");
  pch = strtok(str, ",="); // get first token
  int count = 0;
  String latitude, longitude;
  while (pch != NULL) {
    Serial.print("string found ");
    Serial.println(pch); // print it
    if (count == 3) {
      Serial.println("lat found");
      latitude = pch;
    }
    if (count == 4) {
      Serial.println("long found");
      longitude = pch;
    }
    count++;
    pch = strtok(NULL, ",|"); // get next token
  }
  Serial.print("latitude ");
  Serial.println(latitude);
  Serial.print("longitude ");
  Serial.println(longitude);
}

void loop() {}

```

the serial montor prints

```cpp
Splitting string +RCV=2,20,41.000583,21.134611|,-34,11 into tokens:
string found +RCV
string found 2
string found 20
string found 41.000583
lat found
string found 21.134611
long found
string found -34
string found 11
latitude 41.000583
longitude 21.134611

```

after tokenising the Strins latitude and longitude contains the values with you can then transmit over MQTT - no need to convert to doubles

if you received packets are terminated by newline you could try

```cpp
String incomming = Serial2.readStringUntil('\n');

```

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 7:43am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/7 "2023-01-09T07:43:45Z")

</div>

Hello @horace ! Thanks for keep supporting. I appreciated.

Please allow me sometime to upload and run with your provided code. Thanks.

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 8:03am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/8 "2023-01-09T08:03:29Z")

</div>

a better alternative may be to use sscanf() and check it has converted the two values OK

```cpp
// strtok example - parse tokens

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  char str1[] = "+RCV=2,20,41.000583,21.134611|,-34,11";
  double latitude, longitude;
  if (sscanf(str1, "+RCV=%*d,%*d,%lf,%lf", &latitude, &longitude) == 2) {
    Serial.println("converted two doubles OK");
    Serial.print("latitude ");
    Serial.println(latitude,10);
    Serial.print("longitude ");
    Serial.println(longitude,10);
  }
}

void loop() {}

```

gives

```cpp
converted two doubles OK
latitude 41.0005830000
longitude 21.1346110000

```

if you receive corrupt data the sscanf() will fail and you don't transmit rubish over MQTT

just for interest how far apart are your transmitter and receiver?

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 8:16am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/9 "2023-01-09T08:16:56Z")

</div>

Hello @horace ! I have tried to uplaod your first one provided code, but sorry to say that nothing happned, even got an error run time error i.e. latitude & longitude is not declared in this scope.

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 8:19am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/10 "2023-01-09T08:19:24Z")

</div>

> [@horace](#):
>
> just for interest how far apart are your transmitter and receiver?

hello @horace ! they are just 10meter apart only to working out with them.

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 8:19am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/11 "2023-01-09T08:19:31Z")

</div>

I guess you did not define them

```cpp
String latitude, longitude;

```

try the sscanf() version - it is simpler and does error checking

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 8:22am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/12 "2023-01-09T08:22:57Z")

</div>

> [@horace](#):
>
> I guess you did not define them
> 
> ```arduino
> String latitude, longitude;
> 
> ```

Now i defined them as,  
String latitude, longitude;

Now upload and run the code and there is no change in the serial monitor output , its just sending the same data as mentioned earlier.

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 8:37am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/13 "2023-01-09T08:37:36Z")

</div>

try the scanf() version  
if it does not work post the code

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 9:07am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/14 "2023-01-09T09:07:34Z")

</div>

> [@horace](#):
>
> if it does not work post the code

Hello @horace ! Please have review the code to fix the issue. Thanks.

```arduino
#include <WiFi.h>
#include <PubSubClient.h>
#define RXD2 16
#define TXD2 17

//TODO: ESP32 MQTT user config
const char* ssid = " "; // Wifi SSID
const char* password = " "; // Wifi Password
const char* mqtt_username = "user"; // username
const char* mqtt_password = " ";
const char* pubTopic = " "; // topic
const unsigned int writeInterval = 25000; // write interval (in ms)

//MQTT config
const char* mqtt_server = "mqtt";
unsigned int mqtt_port = 1883;

// objects
WiFiClient askClient;
PubSubClient client(askClient);

// setup
void setup() {
Serial.begin(115200);
 char str1[] = "+RCV=2,20,41.000583,21.134611|,-34,11";
  double latitude, longitude;
  if (sscanf(str1, "+RCV=%*d,%*d,%lf,%lf", &latitude, &longitude) == 2) {
    Serial.println("converted two doubles OK");
    Serial.print("latitude ");
    Serial.println(latitude,10);
    Serial.print("longitude ");
    Serial.println(longitude,10);
  }

Serial.println(" *****************************************************");
Serial.println(" ********** Program Start : ESP32 publishes GPS position to MQTT");
Serial.print(" ********** connecting to WIFI : ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("->WiFi connected");
Serial.println("->IP address: ");
Serial.println(WiFi.localIP());

client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);

Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);
}

// loop
void loop() {

if (!client.connected())
reconnect();
client.loop();
// This sketch displays information every time a new sentence is correctly encoded.
            
  if (Serial2.available()) {            
    String incomming = Serial2.readString();
    Serial.println(incomming);
    
    Serial.println(" ********** Publish MQTT data");
char mqtt_payload[50] = "";
printf (mqtt_payload, 50, "m1=%lf;%lf", latitude, longitude);
Serial.print("Publish message: ");
Serial.println(mqtt_payload);
client.publish(pubTopic, mqtt_payload);
Serial.println("> MQTT data published");
Serial.println(" ********** End ");
Serial.println(" *****************************************************");

delay(writeInterval);// delay
} else {
Serial.println(F("INVALID"));
}
}

//MQTT callback
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
//MQTT reconnect
void reconnect() {

// Loop until we're reconnected
while (!client.connected()) {
Serial.print(" ********** Attempting MQTT connection...");

// Attempt to connect
if (client.connect("ESP32Client", mqtt_username, mqtt_password)) {
Serial.println("-> MQTT client connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println("-> try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

```

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 9:22am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/15 "2023-01-09T09:22:23Z")

</div>

try

```cpp
#include <WiFi.h>
#include <PubSubClient.h>
#define RXD2 16
#define TXD2 17

//TODO: ESP32 MQTT user config
const char* ssid = " "; // Wifi SSID
const char* password = " "; // Wifi Password
const char* mqtt_username = "user"; // username
const char* mqtt_password = " ";
const char* pubTopic = " "; // topic
const unsigned int writeInterval = 25000; // write interval (in ms)
//MQTT config
const char* mqtt_server = "mqtt";
unsigned int mqtt_port = 1883;

// objects
WiFiClient askClient;
PubSubClient client(askClient);

// setup
void setup() {
  Serial.begin(115200);
  Serial.println(" *****************************************************");
  Serial.println(" ********** Program Start : ESP32 publishes GPS position to MQTT");
  Serial.print(" ********** connecting to WIFI : ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("->WiFi connected");
  Serial.println("->IP address: ");
  Serial.println(WiFi.localIP());

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);
}

// loop
void loop() {

  if (!client.connected())
    reconnect();
  client.loop();
  // This sketch displays information every time a new sentence is correctly encoded.

  // read packet into incomming array
  if (Serial2.available()) {
    char incomming[100] = { 0 };
    Serial2.readBytes(incomming, 100);
    Serial.print("incomming ");
    Serial.println(incomming);
    // parse incomming for lat and long
    double latitude, longitude;
    if (sscanf(incomming, "+RCV=%*d,%*d,%lf,%lf", &latitude, &longitude) == 2) {
      Serial.println("converted two doubles OK");
      Serial.print("latitude ");
      Serial.println(latitude, 10);
      Serial.print("longitude ");
      Serial.println(longitude, 10);

      Serial.println(" ********** Publish MQTT data");
      char mqtt_payload[50] = "";
      printf(mqtt_payload, 50, "m1=%lf;%lf", latitude, longitude);
      Serial.print("Publish message: ");
      Serial.println(mqtt_payload);
      client.publish(pubTopic, mqtt_payload);
      Serial.println("> MQTT data published");
      Serial.println(" ********** End ");
      Serial.println(" *****************************************************");

      delay(writeInterval); // delay
    } else {
      Serial.println(F("INVALID"));
    }
  }
}

//MQTT callback
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}
//MQTT reconnect
void reconnect() {

  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print(" ********** Attempting MQTT connection...");

    // Attempt to connect
    if (client.connect("ESP32Client", mqtt_username, mqtt_password)) {
      Serial.println("-> MQTT client connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println("-> try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 12:03pm UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/16 "2023-01-09T12:03:49Z")

</div>

Hello @horace ! i have uploaded and run your updated code, but sorry to say that its not working properly receiving corrupt data and mqqt server is sending error msg. Thanks.

![gps_data_serial_monitor_screenshot_3](https://europe1.discourse-cdn.com/arduino/original/4X/9/3/6/936660180d8de60437f3eadcfdc9b1d8721b403e.png)

MQTT server payload output:

 ![mqtt_server_Screenshot_1](https://europe1.discourse-cdn.com/arduino/original/4X/a/3/7/a37f98d6e829e2eb684297402df67f9280b80978.png)

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 9, 2023, 12:27pm UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/17 "2023-01-09T12:27:21Z")

</div>

try replace the printf()

```cpp
printf(mqtt_payload, 50, "m1=%lf;%lf", latitude, longitude);

```

with sprintf()

```cpp
      sprintf(mqtt_payload,"m1=%lf;%lf", latitude, longitude);

```

you should then see the message being sent over MQTT

```cpp
********** Publish MQTT data
Publish message: m1=41.000583;21.134611

```

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 9, 2023, 12:52pm UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/18 "2023-01-09T12:52:16Z")

</div>

Hello @horace ! Thanks a lot. fixed the issue. Now getting data smoothly at serial monitor and mqtt server. I really appreciated your support to fix the issue.

---

<div class="post-metadata">

**Author:** ![kpin404](https://avatars.discourse-cdn.com/v4/letter/k/cab0a1/32.png) [@kpin404](https://forum.arduino.cc/u/kpin404)\
**Post date:** [January 10, 2023, 4:35am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/19 "2023-01-10T04:35:14Z")

</div>

Hello @horace! Next could you please assist me a bit more further that what LoRaWAN gateway to use with many of these Reyax based remote GPS lora transmitter nodes moving at different locations to monitor the different objects' locations on a cloud based plateform? Would be any LoRaWAN gateways are compitable with this and/or need to be compitable with this Reyax based lora module required for LoRaWAN gateway? Thanking you.

---

<div class="post-metadata">

**Author:** ![horace](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/horace/32/1014299_2.png) [@horace](https://forum.arduino.cc/u/horace)\
**Post date:** [January 10, 2023, 6:35am UTC](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066/20 "2023-01-10T06:35:38Z")

</div>

as you have indicated the problem of the current thread is solved and if you are moving to a new topic perhaps you should start a new thread

which LoRa modules are you planning to use?  
the [rylr998](https://reyax.com/products/rylr998/) documentation does not mention LoRaWAN just long range LoRa communication  
Due to its complexity LoRaWAN requires a much more powerful internal processor than simple LoRa peer-to-peer hence you find some LoRa devices do not support LoRaWAN

if the device does support LoRaWAN any Gateway of the correct frequency etc should work with it  
if setting the LoRaWAN device up in a city you may well find there are Gateways in range and it just works.  
If there are none you need to set up your own gateway -

1. if you have access to local WiFi there are LoRaWAN gateways which connect to the TTN network, e.g. I have [The Things Gateway](https://www.thethingsnetwork.org/docs/gateways/gateway/) and a [The Things Indoor Gateway](https://www.thethingsnetwork.org/docs/gateways/thethingsindoor/) which I use when traveling
2. there are LoRaWAN gateways with GSM Modems - you would require power which may be mains or solar etc

have a look at [LoRaWAN gateways](https://www.thethingsnetwork.org/docs/gateways/)

[Next page](https://forum.arduino.cc/t/arduino-code-for-gps-data-via-lora-node-to-mqtt-server/1075066.md?page=2)
