Real-Time GPS Tracking

by elizabethna in Circuits > Raspberry Pi

9939 Views, 22 Favorites, 0 Comments

Real-Time GPS Tracking

giffy.gif

In this tutorial, we will show you how to do real-time location tracking using a BerryGPS-GSM, a Raspberry Pi Zero, and Initial State. We will send longitude, latitude and speed via 3G with the BerryGPS-GSM to Initial State.

Supplies

Initial State

49104618-03c8f680-f244-11e8-917b-e6a48e781fd1.png

We want to stream all of our longitude, latitude, and speed data to a cloud service and have that service turn our data into a nice dashboard that we can access from our laptop or mobile device. We will use Initial State.

Step 1: Register for Initial State Account

Go to https://iot.app.initialstate.com and create a new account. You get a 14 day free trial and anyone with an edu email address can register for a free student plan.

Step 2: Install the ISStreamer

Install the Initial State Python module onto your Raspberry Pi. In the command prompt, run the following command:

$ cd /home/pi/
$ \curl -sSL https://get.initialstate.com/python -o - | sudo bash

Step 3: Make some Automagic

After Step 2 you will see something similar to the following output to the screen:

pi@raspberrypi ~ $ \curl -sSL https://get.initialstate.com/python -o - | sudo bash
Password: Beginning ISStreamer Python Easy Installation! This may take a couple minutes to install, grab some coffee :) But don't forget to come back, I'll have questions later! Found easy_install: setuptools 1.1.6 Found pip: pip 1.5.6 from /Library/Python/2.7/site-packages/pip-1.5.6- py2.7.egg (python 2.7) pip major version: 1 pip minor version: 5 ISStreamer found, updating... Requirement already up-to-date: ISStreamer in Library/Python/2.7/site-packages Cleaning up... Do you want automagically get an example script? [y/N] Where do you want to save the example? [default: ./is_example.py] Please select which Initial State app you're using: 1. app.initialstate.com 2. [NEW!] iot.app.initialstate.com Enter choice 1 or 2: Enter iot.app.initialstate.com user name: Enter iot.app.initialstate.com password:

When asked if you want to automagically get an example script put "y" for yes and press enter to save your script in the default location. For the question about which app you are using, select 2 (unless you signed up before November 2018) and enter your username and password.

Step 4: Run the Example Script

Run the test script to make sure we can create a data stream to your Initial State account. Write the following command:

$ python is_example.py 

Step 5: Example Data

Go back to your Initial State account in your web browser. A new data bucket called “Python Stream Example” should have shown up on the left in your log shelf (you may have to refresh the page). Click on this bucket to view your data.

BerryGPS-GSM & Raspberry Pi Zero

BerryGPS-GSM-PiZero600.jpg

If you are using a BerryGPS-GSM, you can follow this guide to get the GPS working and get your Pi to connect via 3G using PPP.

The linked guide also shows how to make your Pi connect to the carrier network automatically when booted. You will need this if you plan to perform remote tracking.

Install Libraries

You will need to install the following libraries:

$ sudo apt-get install python-pip
$ sudo pip install pynmea2
$ sudo pip install ISStreamer 

Main Python Script

Here we will create the main script which will stream the GPS data to Initial State.The code below creates a separate thread which is used to monitor the serial port. This is needed because we have a pause in the main loop. The pause is there to limit how much data we upload over 3G.

If we did everything in the same thread during the pause, the serial buffer would fill up (it is FIFO) and when we get the next value from the buffer, it will be old by a few seconds. This happens every loop and eventually the data will be minutes or hours behind.

To create the python script and open the text editor enter the following command:

$ nano GPStracker.py 

Copy and paste the following code into the text editor. You will need to enter your Initial State Access Key on line 11 where is says "ENTER YOUR ACCESS KEY":

#! /usr/bin/python<br>from gps import *
from time import *
import threading
import datetime
from ISStreamer.Streamer import Streamer
  
gpsd = None #Setup global variable 
  
#Setup the Initial State stream, enter your access key below
streamer = Streamer(bucket_name="GPS_Tracker", bucket_key="GPS_TRACKER", access_key="ENTER YOUR ACCESS KEY")
  
class GPSDcollector(threading.Thread):
    def __init__(self, threadID):
        threading.Thread.__init__(self)
        self.threadID = threadID
        global gpsd #bring it in scope
        gpsd = gps(mode=WATCH_ENABLE) #Start GPSD
        self.running = True #Start running this thread
    def run(self):
        global gpsd
        while gpsdThread.running:
            gpsd.next() 
  
if __name__ == '__main__':
    gpsdThread = GPSDcollector(1) # create a thread to collect data
    try:
        gpsdThread.start() # start it up
        while True:
            print 'GPS ', gpsd.utc,'--> CPU time->', datetime.datetime.now().time(),
            if (gpsd.fix.longitude<>0) and (gpsd.fix.longitude<>'nan'):
                streamer.log("Location", "{lat},{lon}".format(lat=gpsd.fix.latitude,lon=gpsd.fix.longitude))
                streamer.log("speed",gpsd.fix.speed)
            print '  lat    ' , gpsd.fix.latitude,
            print '  lon   ' , gpsd.fix.longitude,
            print '  speed ', gpsd.fix.speed
  
            sleep(5)
    except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
        print "\nKilling Thread..."
        gpsdThread.running = False
        gpsdThread.join() # wait for the thread to finish what it's doing
    print "Done.\nExiting."

Save and exit the text editor my pressing CTRL + X, Y, enter.

Start the script automatically on boot

If you are doing remote monitoring, you would want the script to run on boot. To do this, we will create a small script which will start the main python program. Enter the following command:

$ nano GPStrackerStart.sh 

Copy the lines into the text editor:

#!/bin/bash
sleep 15
python /home/pi/GPStracker.py & 

The pause above is there to give the Pi time to boot and connect via PPP.

Make the script executable:

$ chmod +x ~/GPStrackerStart.sh 

We will use cron to start the script every time the Pi boots:

$ crontab -e 

Add the below line to the bottom:

@reboot /home/pi/GPStrackerStart.sh &

Location & Speed Dashboard

berry.png

Now that you have your project up and running data should be sending to Initial State. You'll have GPS data and speed data. You can use the GPS data in a maps Tile to track location. For the map Tile, make sure to check the Draw Path checkbox so that your location tracking is mapped out like the dashboard above. You can put your speed data in a line graph to see speed over time.