IoT Based GPS Tracking using NodeMCU and Matlab Visualization on ThingSpeak

IoT Based GPS Tracking using NodeMCU

Ever wondered how your phone software pinpoints your location while driving using GPS? The answer to this is that a small GPS module embedded in your phone communicates with a network of satellites to determine the location of your phone. In this project, we are going to understand how a GPS module works, and we will get acquainted with one of the popular GPS receiver module called NEO 6M, this module differs in size from the one used in mobile phones but the working is same. By using the information provided by the GPS receiver module and the Thingspeak IoT platform, we will try to plot the data on the graph. In addition to this, we will also visualize the location on the satellite view map by generating a URL using the inbuild function in the Thingspeak- Matlab visualization (needs coding, which is explained in the code explanation section). By using this URL, anyone from any browser can track the location of the GPS device to which it is attached. If you are looking for a simple solution you can also check out the NodeMCU GPS Webserver project which is also very similar to what we are about to build. 

 

Components Required

  • NEO 6M GPS module
  • Node MCU
  • Connecting wires

 

How does a GPS Module work?

GPS stands for Global Positioning System, which is a worldwide radio-navigation system. To track the location of the device, the GPS tracking system uses the Global Navigation Satellite System (GNSS) Network. This network consists of a range of satellites that uses microwave signals to transmit the data which will be received by the GPS receiver module.

 

The GPS Satellite Constellation consists of 24 Earth-orbiting GPS satellites. These satellites are positioned in such a way that at any moment of time at least 6 of them always lie within the line of sight from anywhere on the Earth’s surface. When it comes to pinpointing the location of the GPS device, the system follows a simple mathematical principle called trilateration.

Global Positioning System

 

For example, consider a satellite A. When you turn on the mobile GPS, it receives the satellite A’s current time and position. Now the receiver then calculates the distance from the satellite A by calculating the time and speed of the signal (speed of the signal is equal to the speed of the light). The receiver by now knows that it has to lie on the circle formed by satellite A’s distance. Now the GPS receiver gets the data from another satellite, let’s say satellite B. By using the data provided by the satellite B, it knows that it has to lie on the interaction point between these two circles (formed by satellite A and B). Now it takes the data from the third satellite to pinpoint the exact location. This procedure of pinpointing your location by using the satellite's data like time and position Is known as Trilateration.

 

NEO 6M GPS Receiver Module

So, now in our project, we will be using the NEO 6M GPS receiver module, which consists of 50 channels. These channels are like rooms and each channel can accommodate one frequency per satellite. These channels are usually operated in parallel, which allows the receiver to maintain accuracy while the receiver is moving. The time to first fix (TTFF) is the time required to receive the satellite signals and navigation signals and calculate the position using that data. The TTFF for NEO 6M is 27 sec for cold start and warm start, and 1 sec for the hot start.

NEO 6M GPS Receiver Module Pinout

When it comes to the operating conditions, the maximum operating voltage is 3.6V and the minimum operating voltage is 2.7V. The average supply current for the NEO 6M module is 39mA. In some modules, there is an inbuilt 3.3V voltage regulator. So, we can connect the module to 5V for max performance. For communication, the module uses UART, which will be easy to communicate with any MCU (Node MCU). The connection part is discussed in the circuit diagram section. The modules pinout is shown below:

 

Testing the Neo 6M GPS Module

To know if the GPS module is working or not, connect the module as shown in the below circuit diagram and upload an empty code. Note that, if you are uploading an empty code, then the serial communication will take place using the default TX and RX pins of the nodeMCU. To check the data on the serial monitor, change the circuit accordingly i.e. connect the GPS module’s RX and TX to NodeMCU RX and TX as shown below

Neo 6M GPS Module

 

After uploading the empty code,  open the serial monitor. By now, you should be seeing some values being printed on the screen. Wait, they are not the correct values. If you observe, you can find that some bits are missing in the output. At first, it takes some time for the module to give the correct values. Note: if the GPS module starts to blink, it means that the module is receiving the values. The below pic shows when the received data has some bits missing in them.

Serial Monitor

 

If the data doesn’t have bits missing, then the data will be like the following pic.

Serial Monitor Data Value

 

The above data that you are seeing is the data being represented by NMEA format. NMEA stands for National Marine Electronics Association. This standard data format is supported by all GPS manufacturers just like ASCII for computer manufactures.

GPGSV – Tells about the GPS satellites in view

1    = Total number of messages of this type in this cycle

2    = Message number

3    = Total number of SVs in view

4    = SV PRN number

5    = Elevation in degrees, 90 maximum

6    = Azimuth, degrees from true north, 000 to 359

7    = SNR, 00-99 dB (null when not tracking)

8-11 = Information about second SV

12-15= Information about third SV

16-19= Information about the fourth SV

 

GPGLL – Geographic Positioning, latitude, and longitude. For example in $GPGLL,4815.45,N,12311.12,W,215455,A

           4815.46, N    Latitude 48 deg. 15.45 min. North
           12311.12, W   Longitude 123 deg. 11.12 min. West
           215455        Fix taken at 12:54:55 UTC
             A           Data valid

 

Circuit Diagram for GPS Tracker

The connections between the node MCU and the NEO 6M module is simple. The VCC and GND pin of the NEO 6M module is connected to the positive and negative power rail of the breadboard, and the 3v3 and GND pin of the node MCU is connected to the positive and negative power rail of the breadboard as shown in the below fig. The RX and TX pin of the NEO 6M is connected to the D1 and D2 pins of the node MCU. The Node MCU is powered by using USB.

GPS Tracker Circuit Diagram 

 

Setting up Thingspeak

At first, signup for thingspeak account if you are a new user. We already built many interesting projects using Thingspeak, you can also check them out.

After signing up, select the channels. After selecting channels, select New channel.

ThingSpeak Sign in

 

After selecting the new channel,  the below page will be loaded. Enter the details and appropriate fields name and click save.

ThingSpeak for GPS Tracking

 

After selecting save, the below page will be loaded. Now select the option API keys

 ThingSpeak API Key

 

After selecting the API keys, the below page will be loaded. Now, Note down the Channel ID, Write Key and Read Key. Write key is used in the nodeMCU programming while the Read key is used in the Matlab visualization program.

 ThingSpeak API Key

 

after this, select the private view option and click on the Matlab visualization option.

MATLAB Visualization

 

Now, the below page will be loaded. Change nothing and select Create.

MATLAB Visualization Configuration

 

Now, you will be loaded a page, where you can write the code for pointing the location on the map using the latitude and longitude. Copy-paste the code, which is provided in this article, and change the needed values( Read Key and channel ID).

MATLAB Visualization

 

Check on the create a public URL box so that by using this URL anyone can find the location of the device.

GPS Tracking Public URL

 

Next, we need two different types of programs. One code deals with acquiring the data from the GPS module and then to transmit the data to thingspeak. The second code deals with pointing the location on the map using the data which is sent to the thingspeak. The first is written in the Arduino IDE, while the second code is written in the thingspeak Matlab visualization.

 

Before getting into the code explanation, there are certain libraries which are needed to be downloaded, which helps in the conversion of raw data (NMEA format) to an understandable data. First, download the tinyGPS library using the provided link. Next, download the thingspeak library by searching it in the library manager. Download the one which is provided by MathWorks.

 

NodeMCU program to read GPS data and send to Thingspeak

The complete program can be found at the bottom of this page, the explanation of the same is as follows. The below snippet is used to include the libraries, which are needed for our code to work without any errors, and Setting the GPIO pins 4 and 5 as RX and TX pins of the NodeMCU. The GPS baud rate is set to 9600.

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
static const int RXPin = 4, TXPin = 5;
static const uint32_t GPSBaud = 9600;

 

The below code runs only when there is incoming data from the GPS module. The code encodes the data and if the encoded data is valid, then the data is considered, and further calculation is done to transform the NMEA data to the understandable data. The below code only sends the latitude and longitude values to the thingspeak.

  while (ss.available() > 0){
    if (gps.encode(ss.read()))
    {
      if (gps.location.isValid())
      {
        latitude = gps.location.lat();
        lat_str = String(latitude , 6);
        longitude = gps.location.lng();
        lng_str = String(longitude , 6);
        Serial.print("Latitude = ");
        Serial.println(lat_str);
        Serial.print("Longitude = ");
        Serial.println(lng_str);
        ThingSpeak.setField(1, lat_str);
        ThingSpeak.setField(2, lng_str);
        ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
      }
     delay(1000);
     Serial.println(); 
    }
  }
}

 

Matlab ThingSpeak Visualization code to display location on Map

Now, we have to write a code, which can point the location on the map by using the latitude and longitude values, which are transferred to the thingspeak. The below screenshot shows you the example URL.

MatLab Thingspeak Visualization Code

 

The below code takes the values of the last 10 values and locates them on the map. By using the URL, which will be available after running the code. To change the number of values, it needs to consider change the value which is written after the ‘NumPoints’.

% Enter your MATLAB code below

lat = thingSpeakRead(******,'Fields',1,'ReadKey','****************','NumPoints',10,'Timeout',50);
lon = thingSpeakRead(******,'Fields',2,'ReadKey','****************','NumPoints',10,'Timeout',50);

 

The below code pinpoints the location on the map using the latitude and longitude, which are provided by the nodeMCU.

geoscatter(lat,lon,'h');
geobasemap('streets');    

 

Once your programming is complete your page should look like something as shown below

MATLAB Code for GPS Tracker

 

By using the provided URL, I got the below pic in the web browser.

ThingSpeak GPS Tracking

 

Matlab Visualization takes the data from the fields and then locates them on the map. The below pic shows the data being plotted on the fields, which will be further used for Matlab visualization.

ThingSpeak GPS Tracking

 

Testing the NodeMCU GPS Tracker

As soon as you power up the nodeMCU, the readings seen in the serial monitor may not be correct. It takes some finite time to get the correct readings. You will know that the readings are correct if the GPS module starts blinking. Once the nodeMCU gets connected with a LAN, and the GPS data is valid, then this data will be sent to the thingspeak. You can check the data being updated on the fields of the Thingspeak. By using the generated URL, which we got in the Matlab visualization, we can trace the location from any browser.

IoT Based GPS Tracker

The complete working can also be found in the video linked below. If you have any questions, please leave them in the comment section.

Code

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
static const int RXPin = 4, TXPin = 5;
static const uint32_t GPSBaud = 9600;
float latitude , longitude;
String  lat_str , lng_str;
// repace your wifi username and password
const char* ssid     = "Mamameya";
const char* password = "244466666";
unsigned long myChannelNumber = 991048;
const char * myWriteAPIKey = "RX9R15V8GH3941CK";
// The TinyGPS++ object
TinyGPSPlus gps;
WiFiClient  client;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
void setup()
{
  Serial.begin(115200);
  ss.begin(GPSBaud);
  Serial.print("Connecting to ");
  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());
  Serial.print("Netmask: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  ThingSpeak.begin(client);
}
void loop()
{
  while (ss.available() > 0){
    if (gps.encode(ss.read()))
    {
      if (gps.location.isValid())
      {
        latitude = gps.location.lat();
        lat_str = String(latitude , 6);
        longitude = gps.location.lng();
        lng_str = String(longitude , 6);
        Serial.print("Latitude = ");
        Serial.println(lat_str);
        Serial.print("Longitude = ");
        Serial.println(lng_str);
        ThingSpeak.setField(1, lat_str);
        ThingSpeak.setField(2, lng_str);
        ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); 
      }
     delay(1000);
     Serial.println();  
    }
  }
}

Video

20 Comments

I and my pals were found to be reviewing the good guides found on the website and then all of the sudden came up with a horrible suspicion I had not thanked the web blog owner for those strategies. Most of the people happened to be as a result joyful to learn all of them and have in effect honestly been enjoying them. We appreciate you turning out to be well thoughtful and for making a choice on varieties of really good information most people are really desirous to discover. Our own honest apologies for not saying thanks to you earlier.

I precisely wanted to thank you very much all over again. I'm not certain the things I would have implemented without those methods provided by you about this industry. It was a very frightening crisis in my position, however , finding out the specialised technique you dealt with that took me to cry over delight. Extremely happy for this work and hope that you realize what an amazing job that you're doing educating other individuals with the aid of your websites. I'm certain you've never met all of us.

I'm writing to let you understand what a great encounter my cousin's princess experienced viewing your web site. She discovered numerous issues, with the inclusion of what it is like to have an incredible giving style to let folks easily know some complex topics. You undoubtedly exceeded our own expectations. Thanks for producing the insightful, trustworthy, explanatory and in addition unique guidance on this topic to Emily.

I not to mention my friends came going through the great ideas from your web page then unexpectedly got a terrible suspicion I had not thanked you for those techniques. These young boys became totally thrilled to study them and already have seriously been taking advantage of them. Many thanks for turning out to be really accommodating and for considering some amazing information most people are really eager to understand about. My very own honest regret for not saying thanks to earlier.

Needed to write you one little note so as to say thank you over again just for the nice methods you have featured on this website. It was simply pretty open-handed of you giving unhampered what most of us would've distributed for an e book to make some bucks on their own, even more so given that you could possibly have done it if you ever wanted. These ideas in addition acted to be the fantastic way to be sure that many people have the same dream really like mine to know great deal more with regard to this condition. I know there are thousands of more pleasurable occasions up front for those who scan your site.

I want to voice my gratitude for your kindness for women who really want help with this one field. Your real commitment to passing the message all through turned out to be amazingly powerful and have in every case allowed ladies like me to reach their targets. Your entire useful key points signifies a whole lot a person like me and far more to my office workers. Thanks a lot; from everyone of us.

I not to mention my friends were found to be viewing the best guidelines found on your web blog then at once got a terrible feeling I had not thanked the web site owner for those techniques. These young boys had been so passionate to study all of them and already have surely been making the most of them. Thanks for really being quite accommodating and for choosing variety of beneficial guides most people are really eager to learn about. My sincere regret for not expressing gratitude to you earlier.

A lot of thanks for each of your work on this site. My mother loves setting aside time for internet research and it's simple to grasp why. Most people learn all regarding the powerful means you offer simple information through your website and even increase contribution from some others about this article and our child is certainly being taught a great deal. Take pleasure in the remaining portion of the new year. Your carrying out a powerful job.

I must get across my love for your kind-heartedness in support of people who require help on this one idea. Your personal dedication to passing the message along became surprisingly beneficial and have in most cases empowered employees like me to achieve their goals. Your amazing important advice denotes a whole lot to me and somewhat more to my mates. With thanks; from all of us.

I want to convey my respect for your kind-heartedness for men and women who require help on this particular idea. Your special commitment to getting the message around became certainly important and has all the time helped some individuals just like me to arrive at their ambitions. Your own valuable facts can mean this much a person like me and substantially more to my office workers. With thanks; from each one of us.

I want to show some thanks to you just for rescuing me from this particular circumstance. Right after researching through the search engines and obtaining basics which were not productive, I thought my entire life was well over. Being alive devoid of the approaches to the issues you have resolved by way of your write-up is a crucial case, as well as ones that might have badly damaged my career if I had not noticed your web site. Your talents and kindness in touching a lot of stuff was very helpful. I am not sure what I would've done if I hadn't discovered such a subject like this. I'm able to at this time look ahead to my future. Thanks a lot so much for your high quality and amazing help. I won't be reluctant to propose your web page to anyone who ought to have care on this matter.

I'm just commenting to let you be aware of what a notable discovery my daughter found reading the blog. She mastered some pieces, which included what it's like to possess a very effective giving nature to get certain people effortlessly master specified impossible subject areas. You undoubtedly did more than readers' desires. Many thanks for producing the interesting, trustworthy, revealing and as well as fun thoughts on the topic to Ethel.

I must express my gratitude for your kindness in support of persons that really want help on in this subject matter. Your special dedication to passing the solution all through was extremely beneficial and have in most cases helped individuals much like me to get to their pursuits. This warm and helpful help means much a person like me and extremely more to my mates. Thank you; from each one of us.

I must point out my love for your kind-heartedness giving support to folks that actually need help on this content. Your personal dedication to getting the solution all through had become remarkably important and has enabled girls just like me to achieve their ambitions. Your entire valuable tips and hints entails much a person like me and much more to my fellow workers. Thanks a ton; from each one of us.

I precisely wanted to appreciate you yet again. I am not sure what I would have used in the absence of these ways revealed by you over that field. It had become an absolute traumatic matter in my circumstances, nevertheless taking a look at this well-written form you managed that forced me to weep over contentment. Now i'm happy for this service and then believe you comprehend what an amazing job you are putting in educating other individuals using your blog. Most probably you haven't come across any of us.

Thanks for all of the efforts on this web page. Kate delights in conducting internet research and it is easy to see why. Many of us notice all regarding the dynamic form you offer valuable solutions on this web blog and strongly encourage response from some others on this concept then our princess has been being taught a whole lot. Enjoy the rest of the new year. You are doing a stunning job.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.