Category Archives: BerryGPS

Using python with a GPS receiver on a Raspberry Pi

Here are three examples of how to  use python to get GPS data from a GPS receiver attached to a Raspberry Pi.

  1. Using GPSD client libraries
  2. Manually parsing NMEA sentences
  3. Using  pynmea2 to parse NMEA sentences

GPSD client libraries

The gpsd client libraries are based on JSON. The JSON objects have a "class" attribute (E.g. TPV,  SKY, DEVICE.etc...)  which can be used to filter on different information.

This guide shows how to get gpsd up an running on a Raspberry Pi.

The example python  script below filters on the TPV class, which is the Time Position Velocity report and then prints out the relevant information.

#! /usr/bin/python
from gps import *
import time
   
gpsd = gps(mode=WATCH_ENABLE|WATCH_NEWSTYLE) 
print 'latitude\tlongitude\ttime utc\t\t\taltitude\tepv\tept\tspeed\tclimb' # '\t' = TAB to try and output the data in columns.
  
try:

	while True:
		report = gpsd.next() #
		if report['class'] == 'TPV':
			
			print  getattr(report,'lat',0.0),"\t",
			print  getattr(report,'lon',0.0),"\t",
			print getattr(report,'time',''),"\t",
			print  getattr(report,'alt','nan'),"\t\t",
			print  getattr(report,'epv','nan'),"\t",
			print  getattr(report,'ept','nan'),"\t",
			print  getattr(report,'speed','nan'),"\t",
			print getattr(report,'climb','nan'),"\t"
		time.sleep(1) 
except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
	print "Done.\nExiting."

 

 

This python script filters on the SKY class and prints out satellite information.


#! /usr/bin/python
from gps import *
import time
import os
   
gpsd = gps(mode=WATCH_ENABLE|WATCH_NEWSTYLE) 
  
try:
	while True:
		
		report = gpsd.next() #
		if report['class'] == 'SKY':
			os.system('clear')
			print ' Satellites (total of', len(gpsd.satellites) , ' in view)'
			for i in gpsd.satellites:
				print 't', i
		
			print '\n\n'
			print 'PRN = PRN ID of the satellite. 1-63 are GNSS satellites, 64-96 are GLONASS satellites, 100-164 are SBAS satellites'
			print 'E = Elevation in degrees'
			print 'As = Azimuth, degrees from true north'
			print 'ss = Signal stength in dB'
			print 'used = Used in current solution?'
		time.sleep(1) 

except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
	print "Done.\nExiting."

Manually parsing NMEA sentences

The python script below shows how to access GPS data by connecting directly to the serial interface.
It filters on $GPRMC NMEA sentences and then splits the well know attributes into different variables.


import serial
port = "/dev/serial0"
def parseGPS(data):
#    print "raw:", data #prints raw data
    if data[0:6] == "$GPRMC":
        sdata = data.split(",")
        if sdata[2] == 'V':
            print "no satellite data available"
            return
        print "---Parsing GPRMC---",
        time = sdata[1][0:2] + ":" + sdata[1][2:4] + ":" + sdata[1][4:6]
        lat = decode(sdata[3]) #latitude
        dirLat = sdata[4]      #latitude direction N/S
        lon = decode(sdata[5]) #longitute
        dirLon = sdata[6]      #longitude direction E/W
        speed = sdata[7]       #Speed in knots
        trCourse = sdata[8]    #True course
        date = sdata[9][0:2] + "/" + sdata[9][2:4] + "/" + sdata[9][4:6]#date
        print "time : %s, latitude : %s(%s), longitude : %s(%s), speed : %s, True Course : %s, Date : %s" %  (time,lat,dirLat,lon,dirLon,speed,trCourse,date)
def decode(coord):
    #Converts DDDMM.MMMMM > DD deg MM.MMMMM min
    x = coord.split(".")
    head = x[0]
    tail = x[1]
    deg = head[0:-2]
    min = head[-2:]
    return deg + " deg " + min + "." + tail + " min"

print "Receiving GPS data"
ser = serial.Serial(port, baudrate = 9600, timeout = 0.5)
while True:
   data = ser.readline()
   parseGPS(data)

 

Using  pynmea2 to parse NMEA sentences

The python script below shows how to access GPS data by connecting directly to the serial interface.
It filters on $GPGGA NMEA sentences and then uses pynmea2 to parse the data.

Pynmea2 can be installed with;

pi@raspberrypi ~ $ pip install pynmea2
import serial
import pynmea2
port = "/dev/serial0"
def parseGPS(str):
    if str.find('GGA') > 0:
        msg = pynmea2.parse(str)
        print "Timestamp: %s -- Lat: %s %s -- Lon: %s %s -- Altitude: %s %s -- Satellites: %s" % (msg.timestamp,msg.lat,msg.lat_dir,msg.lon,msg.lon_dir,msg.altitude,msg.altitude_units,msg.num_sats)

serialPort = serial.Serial(port, baudrate = 9600, timeout = 0.5)
while True:
    str = serialPort.readline()
    parseGPS(str)

Why does it take so long to get a GPS fix?

Have you ever wondered why it sometimes takes your GPS module 10-20 minutes to get a GPS fix?   This post will explain why.

 

Each satellite sends a message every 30 seconds.  This message consists of two main components;

  • Ephemeris data, used to calculate the position of each satellite in orbit
  • Almanac , which is information about  the time and status of the entire satellite constellation.

Only a small portion of the Almanac is included in a GPS message. It takes 25 messages (12.5 minutes) to get the full Almanac. The full Almanac is needed before a GPS fix can be obtained.  This is Time To First Fix (TTFF).

TTFF is a measure of the time required for a GPS receiver to acquire satellite signals and navigation data, and calculate a position solution (called a fix).

The above happens during a cold start, this is when the GPS module has been off for some time and has no data in its memory. A full Almanac download is required to get TTFF. If the GPS module has clear line of sight to all satellites, the shortest time for TTFF is 12.5 minutes.

In a warm start scenario,  the GPS module has valid Almanac data,  is close to its last position (100km or so) and knows the time  within about 20 seconds. This approximate information helps the receiver estimate the range to satellites.  The TTFF for a warm start can be as short as 30 seconds, but is usually just a couple of minutes.

A receiver that has a current almanac, ephemeris data, time and position can have a hot start. A hot start can take from 0.5 to 20 seconds for TTFF.

 

Smarts phones use Assisted GPS (aGPS), this allows them to download the Ephemeris data and Almanac over the cell network which greatly reduces the TTFF.

BerryGPS Raspberry Pi GPS

 

 

 

Raspberry Pi Embedded Cap With GPS & 10DOF

In this post we will show you how to geotag and capture the "attitude"  of photos taken with the Raspberry Pi camera and record these values within the photo itself using EXIF metadata

We used a modified (hacked?) cap to take the images in this post. The cap took photos, geo-tagged and recorded attitude as we walked around Sydney Harbour.

Components used were;

The BerryGPS-IMU was used to capture the GPS coordinates as well as "attitude".   No external antenna was needed as the BerryGPS-IMU includes an internal antenna.

The "attitude" would include values such as pitch, roll, direction. Some of this data you can see annotate in the image below.


raspberry pi camera gps

Other programs can use some of this data to plot the image on a map and even show the direction of the camera at the time the image was taken.  A good example of this is seen in  GeoSetter

Camera attitude

 

The Cap

The cap has the BerryGPS-IMU sitting on top of the visor, with the Raspberry Pi sitting under the viso.  Some holes where made in the visor to allow connectivity between the BerryGPS-IMU and Raspberry Pi.
We also created a basic camera mount out of 3mm laser cut acrylic. M2.5 Nylon screws were used to hold everything in place.
Raspberry Pi GPS

 

Continue reading Raspberry Pi Embedded Cap With GPS & 10DOF

Navigating with Navit on the Raspberry Pi

 

Navit is an open source navigation system with GPS tracking.
It works great with a Raspberry Pi,  a GPS module and a small TFT with touch, jut like the official Raspberry Pi Display or PiScreen.

 

In this guide, we will be using;

Setting up the GPS

Navit can be installed without a GPS connected to your Raspberry Pi, but you will not be able to use the real-time turn by turn navigation. You will however be able to browse maps. If you are not going to use a GPS, you can skip to the next step.

As we are using the BerryGPS-IMU, we will be following the guide in the link below.  As most GPS modules use serial to communication, this guide can be followed for other GPS modules.

BerryGPS Setup Guide for the Raspberry Pi

 

The images below shows how we have connected the BerryGPS-IMU to the Raspberry Pi 3 whilst it is in the SmartPi Touch case.


Raspberry Pi Navit GPS

If you plan on testing this out in your car,  you need to be mindfully of where you place your BerryGPS. In my setup and I have placed it in the air vent as shown below, and BerryGPS gets a good strong signal.

Raspberry Pi GPS

If you are using an external antenna, then there is no need to worry about where your BerryGPS is placed.

Continue reading Navigating with Navit on the Raspberry Pi

GPS Data logger using a BerryGPS

This post explains how to log GPS data from a BerryGPS or a BerryGPS-IMU and then how to plot this data onto Google Maps and many other maps E.g. OpenStreet, WorldStreet, National Maps, etc..

Raspberry Pi GPS

1. Setup GPS

Follow the instructions on this page to setup your Raspberry Pi for a BerryGPS-IMU. Ensure GPSD is set to automatically start and confirm that you can see the NMEA sentences when using gpsipe;

pi@raspberrypi ~ $ gpspipe -r

 

2.  Automatically Capture Data on Boot.

We will be using gpspipe to capture the NMEA sentence from the BerryGPS and storing these into a file. The command to use is;

pi@raspberrypi ~ $ gpspipe -r -d -l -o /home/pi/`date +"%Y%m%d-%H-%M-%S"`.nmea

-r = Output raw NMEA sentences.
-d = Causes gpspipe to run as a daemon.
-l = Causes gpspipe to sleep for ten seconds before attempting to connect to gpsd.
-o = Output to file.

The date the file is created is also added to the name.

Now we need to force the above command to run at boot. This can be done by editing the rc.local file.

pi@raspberrypi ~ $ sudo nano /etc/rc.local

 

Just before the last line, which will be 'exit 0', paste in the below line;

gpspipe -r -d -l -o /home/pi/`date +"%Y%m%d-%H-%M-%S"`.nmea

Reboot and confirm that you can see a .nmea file in the home directory.

Continue reading GPS Data logger using a BerryGPS

New Products : BerryGPS and BerryGPS-IMU

We have released two new products:

BerryGPS - GPS for the Raspberry Pi

BerryGPS-IMU - GPS and IMU for the Raspberry Pi

Both GPS modules use the  M10478-A2 from Antenova, which is a high quality GPS module which is able to track 22 satellites and has an internal antenna. This means no external antenna is needed if the module has clear access to sky.  Both feature a SuperCap to store ephemeris data for up to four hours. This and many more features are included.

Raspberry Pi GPS
BerryGPS

 

 

 

Both have been specifically designed for the Raspberry Pi Zero, however they will work with any version of Raspberry Pi.

 

The BerryGPS-IMU also includes all the components found on the BerryIMU.  And is compatible with the existing code in our repository. The BerryGPS-IMU present a lot of sensors in a very, very small package.

 

 

Raspberry Pi GPS
BerryGPS-IMU

 

 

 

Raspberry Pi GPS
BerryGPS-IMU on a Raspberry Pi Zero

 

BerryGPS-IMU
BerryGPS-IMU on Raspberry Pi 2

berrygps-skull