Location Tracker With NodeMCU ESP8266


11,936

22

11

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

Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

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!

1 Person Made This Project!

Recommendations

  • Assistive Tech Contest

    Assistive Tech Contest
  • Reuse Contest

    Reuse Contest
  • Made with Math Contest

    Made with Math Contest

11 Discussions

0
None
AlfiyaM

22 days ago

IT SHOWS TECHNICAL JARGON ON SERIAL MONITOR

0
None
BoneyDas

5 months ago on Step 6

"Arduino: 1.8.10 Hourly Build 2019/05/07 05:33 (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 9600"
Sketch uses 386936 bytes (37%) of program storage space. Maximum is 1044464 bytes.
Global variables use 28892 bytes (35%) of dynamic memory, leaving 53028 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.6
2.6
esptool.py v2.6
Serial port COM9
Connecting....
Chip is ESP8266EX
Features: WiFi
MAC: 84:0d:8e:b1:1c:8b
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 391088 bytes to 284598...
Writing at 0x00000000... (5 %)Traceback (most recent call last):
File "C:\Users\BONNY\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2/tools/upload.py", line 25, in <module>
esptool.main(fakeargs)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 2698, in main
operation_func(esp, args)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 2158, in write_flash
esp.flash_defl_block(block, seq, timeout=DEFAULT_TIMEOUT * ratio * 2)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 104, in inner
return func(*args, **kwargs)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 632, in flash_defl_block
self.ESP_FLASH_DEFL_DATA, struct.pack('<IIII', len(data), seq, 0, 0) + data, self.checksum(data), timeout=timeout)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 354, in check_command
val, data = self.command(op, data, chk, timeout=timeout)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 322, in command
self.write(pkt)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 285, in write
self._port.write(buf)
File "C:/Users/BONNY/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/pyserial\serial\serialwin32.py", line 323, in write
raise writeTimeoutError
serial.serialutil.SerialTimeoutException: Write timeout
the selected serial port serial.serialutil.SerialTimeoutException: Write timeout
does not exist or your board is not connected
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences."
This is my error coming to my code after i upload it on the Arduino IDE

0
None
PriyanshS11

7 months ago

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?

0
None
AinaA9

Question 10 months ago

when I click the serial monitor, it came out as jargon word. please help

Capture.PNG
1 answer
0
None
DinaD12AinaA9

Answer 8 months ago

band on sketch 11500

2
None
SteenL

12 months ago

Well done! On my ESP12F I had to increase delay after connection from 500ms to 800ms to get proper client response to parse.

3 replies
0
None
PCSnelSteenL

Reply 12 months ago

Thank you! Ah, that’s possible. Did you manage to make it succeed?

0
None
SteenLPCSnel

Reply 12 months ago

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.

0
None
PCSnelSteenL

Reply 12 months ago

I’m glad it succeeded. Aha, thanks for the tip!

0
None
PCSnelsagar-unwired

Reply 12 months ago

Thank you so much! Are you the one responsible for the API? In case you are, thank you so much for the API. I used it for this and my project (with all the credits to you) and I passed my project! :)