Location Tracker With NodeMCU ESP8266

43K3877

Intro: Location Tracker With NodeMCU ESP8266

Are you curious about how your NodeMCU can track your location? It's possible, even without a GPS module and without display. The output will be coordinates where you are located and you will see them in your serial monitor.

The following setup was used for NodeMCU 1.0 (ESP-12E Module) with Arduino IDE.

  • Windows 10
  • Arduino IDE v. 1.8.4

STEP 1: What Do You Need

What you need in order to follow this tutorial are the following components:

  • Micro USB cable
  • NodeMCU ESP8266

Furthermore, you will need:

  • LocationAPI (from Unwired Labs)
  • Acces to wifi or a hotspot

STEP 2: Go to Unwired Labs

Geolocation comes in very handy because when your GPS is down, you can still use Geolocation to track your location. Our host that provides geolocation, will be https://www.unwiredlabs.com/. Go to that website and sign up (the orange button in the upper right corner).

STEP 3: Sign Up to Get API Token

On the sign up page, you have to fill in your name, email (your API token will be send to your email) and use case (for example, personal use). Select your account type. The free version will do just fine, but keep in mind that you're limited and can't track your location 24/7. Let's get started!

STEP 4: Check Your Email

Go to your email and you will see your API token. Copy the API token, because you need that for the code we will be using. This is how the email looks like:

Hello!

Thanks for signing up with Unwired Labs LocationAPI! Your API token is 'your API code is here' (without quotes). This will give 100 requests/ day for free - forever.

If you'd like to track 5 devices for free, please respond with the following details and we'll upgrade your account within 12 hours:

1. Deployment type (Hardware/ App/ Other):

2. About your project:

3. Website:

You can login to your dashboard here: https://unwiredlabs.com/dashboard. If you run into trouble or have questions, reply to this email and I'll help you out!

Happy Locating!

Sagar

Unwired Labs

STEP 5: Libraries You Will Need

The next step is to open Arduino and go to manage libraries. You need to install the ArduinoJson library. The other libraries are already built in. When you're ready, you can start writing the code.

STEP 6: Add Code in Arduino to Connect With LocationAPI

Make a new sketch and add the following code in Arduino. Write your own wifi/hotspot name and your password. Paste the API token you received in the email. Upload your code to your NodeMCU.

#include <ESP8266HTTPClient.h>

#include <ArduinoJson.h>

#include "ESP8266WiFi.h"

// your network SSID (name) & network password char myssid[] = "Your wifi/hotspot name"; char mypass[] = "Your password";

// unwiredlabs Hostname & Geolocation Endpoint url const char* Host = "www.unwiredlabs.com"; String endpoint = "/v2/process.php";

// UnwiredLabs API_Token. Signup here to get a free token https://unwiredlabs.com/trial String token = "d99cccda52ec0b";

String jsonString = "{\n";

// Variables to store unwiredlabs response double latitude = 0.0; double longitude = 0.0; double accuracy = 0.0;

void setup(){ Serial.begin(115200);

// Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); Serial.println("Setup done");

// We start by connecting to a WiFi network Serial.print("Connecting to "); Serial.println(myssid); WiFi.begin(myssid, mypass);

while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("."); }

void loop() { char bssid[6]; DynamicJsonBuffer jsonBuffer;

// WiFi.scanNetworks will return the number of networks found int n = WiFi.scanNetworks(); Serial.println("scan done");

if (n == 0 ) { Serial.println("No networks available"); } else { Serial.print(n); Serial.println(" networks found"); }

// now build the jsonString... jsonString = "{\n"; jsonString += "\"token\" : \""; jsonString += token; jsonString += "\",\n"; jsonString += "\"id\" : \"saikirandevice01\",\n"; jsonString += "\"wifi\": [\n"; for (int j = 0; j < n; ++j) { jsonString += "{\n"; jsonString += "\"bssid\" : \""; jsonString += (WiFi.BSSIDstr(j)); jsonString += "\",\n"; jsonString += "\"signal\": "; jsonString += WiFi.RSSI(j); jsonString += "\n"; if (j < n - 1) { jsonString += "},\n"; } else { jsonString += "}\n"; } } jsonString += ("]\n"); jsonString += ("}\n"); Serial.println(jsonString);

WiFiClientSecure client;

//Connect to the client and make the api call Serial.println("Requesting URL: https://" + (String)Host + endpoint); if (client.connect(Host, 443)) { Serial.println("Connected"); client.println("POST " + endpoint + " HTTP/1.1"); client.println("Host: " + (String)Host); client.println("Connection: close"); client.println("Content-Type: application/json"); client.println("User-Agent: Arduino/1.0"); client.print("Content-Length: "); client.println(jsonString.length()); client.println(); client.print(jsonString); delay(500); }

//Read and parse all the lines of the reply from server while (client.available()) { String line = client.readStringUntil('\r'); JsonObject& root = jsonBuffer.parseObject(line); if (root.success()) { latitude = root["lat"]; longitude = root["lon"]; accuracy = root["accuracy"];

Serial.println(); Serial.print("Latitude = "); Serial.println(latitude, 6); Serial.print("Longitude = "); Serial.println(longitude, 6); Serial.print("Accuracy = "); Serial.println(accuracy); } }

Serial.println("closing connection"); Serial.println(); client.stop();

delay(5000); }

STEP 7: Open the Serial Monitor to See If You're Connected

Go to tools in Arduino and open the serial monitor. To see if you're connected to the internet, you should see the following in the serial monitor:

Setup done
Connecting to (your wifi name)
...
scan done

STEP 8: Get the Coordinates

If it worked succesfully, you should see under scan done a whole list of data. The only thing we need is the code under the requesting URL, so we will need the latitude and the longitude. These are the coordinates.

Requesting URL: https://www.unwiredlabs.com/v2/process.php

Connected

Latitude = 52.385259

Longitude = 5.196099

Accuracy = 41.00

closing connection

After 5 seconds the code will constantly update and you will probably see the latitude, longitude and accuracy change. That's because the API is trying it's best to track the location as precisely as possible.

STEP 9: Go to Google Maps

Go to https://www.google.com/maps/ and type your coordinates in the search bar. The coordinates need to be written in the following way: 52.385259,5.196099. Google Maps should show where you're located on the map.

STEP 10: Send Location to Your Mobile

And... You're done! Therefore, if you want to send the location to your mobile, it's possible. Google Maps will then send an email with your coordinates if you want to.

Happy locating!

44 Comments

Hi im sorry to inform you that im getting exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

kindly help me to solve this error please.
arduinojson version maybe is old
getting this error: 'client' does not name a type
please can anyone help
WiFiClientSecure client; // 1
( that line in code )

(after this line , just paste)

client.setInsecure(); // 2
Hi,

I understand this code is a year old and I may be annoying by commenting but I have a school project that would really benefit from this and it is not working.

I first had trouble where it wouldn't print the longitude/latitude at all but adding the "client.setInsecure();" worked to fix that. The problem im now having is that even after raising the delay to 800ms, the long/lat are all 0.

I am on 115200 baud and am using ArduinoJson 5.13.
Any tips?
you have to raise the delay
check if u are a new account
hello , i get an error shown below on an image by the way i'm using ArduinoJson 5 lybrairie and arduno 1.8.2 ide
i see that ur token starts with pk.....
that means , this is a new account , so check settings in unwired labs , wifi locating apì , u'll notice that it is not enabled
Why my scanned is not done?
just keep connecting
I cannot connect to UnwiredLabs server using esp8266. Each time it tries to connect the connection closes with a msg on Serial monitor "Closing Connection", without displaying the location. What should I do?
add the line [ client.setInsecure(); ] after [ WiFiClientSecure client; ]
in program, where we need to add these lines..
if the code isn't working with you just add the line [ client.setInsecure(); ] after [ WiFiClientSecure client; ]
and make sure you use baud rate 115200
i am getting error
client not declared in scope
It still Doesn't work. Code is not giving any error but Lat, Long and Accuracy is not Displayed. Its skips that and diplays Closing Connection. Can you Help out?
Well done! On my ESP12F I had to increase delay after connection from 500ms to 800ms to get proper client response to parse.
Thank you! Ah, that’s possible. Did you manage to make it succeed?
Yes, it succeeded. Not sure where the latency increase was. Also if there is any question on the json string being passed to unwiredlabs.com, there is a nice checker at unwiredlabs.com to make sure the syntax is correct.
I’m glad it succeeded. Aha, thanks for the tip!
More Comments