Real-time GPS tracking with a Raspberry Pi

In this guide, we will show how to do real time tracking, use a BerryGPS-GSM and initialstate.com 

Initialstate has some great tools to easily stream data from a Raspberry Pi to Initialstate.com and show this data within a dashboard using tiles.  We will send longitude,  latitude and  speed. And use a BerryGPS-GSM to get these values and upload them via 3G.

 

You will need to create an account on Initialstate.com and then grab your access key which can be found under "My Settings"

BerryGPS-GSM setup

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

The above 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(E.g. Asset tracking).

Install required libraries

pi@raspberrypi ~ $ sudo apt-get install python-pip
pi@raspberrypi ~ $ sudo pip install pynmea2
pi@raspberrypi ~ $ sudo pip install ISStreamer

 

Main Python Script

Here we will create the main script which will stream the GPS data to Initialstate.com.
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.

The access key below is not a valid key, it is just an example. You will need to replace it with your own key.

pi@raspberrypi ~ $ nano ~/GPStracker.py

#! /usr/bin/python
from gps import *
from time import *
import threading
import datetime
from ISStreamer.Streamer import Streamer
gpsd = None  #Setup global variable 
#Setup the Initialstate stream, give it a bucket name and the access key
streamer = Streamer(bucket_name="GPS_Tracker20190713", bucket_key="GPS_Tracker20190713", access_key="ist_W4aHj0eCkMjCD8JVpp3AMsKomys8NaD")

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'): #Only upload data if it is valid
          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."
  

 

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.

pi@raspberrypi ~ $ nano ~/GPStrackerStart.sh

copy in the below lines;

#!/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;

pi@raspberrypi ~ $ chmod +x ~/GPStrackerStart.sh

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

pi@raspberrypi ~ $ crontab -e

Add the below line to the bottom

@reboot /home/pi/GPStrackerStart.sh &

Other Guides and Tutorials for BerryGPS-GSM

One thought on “Real-time GPS tracking with a Raspberry Pi”

  1. The program works very well, it was tested with a raspberry pi zero and a usb gps u-blox, connected to a cell phone as a hotspot.
    Could you share similar python program but for ubidots ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.