Utiliser python avec un récepteur GPS sur un Raspberry Pi

Utiliser python avec un récepteur GPS sur un Raspberry Pi

Voici trois exemples d’utilisation de python pour obtenir des données GPS à partir d’un récepteur GPS connecté à un Raspberry Pi.

  1. Utilisation des bibliothèques clientes GPSD
  2. Analyse manuelle des phrases NMEA
  3. Utiliser pynmea2 pour analyser des phrases NMEA

le bibliothèques clientes gpsd sont basés sur JSON. Les objets JSON ont un attribut « class » (par exemple TPV, SKY, DEVICE.etc…) qui peut être utilisé pour filtrer sur différentes informations.

Ce guide montre comment faire fonctionner gpsd sur un Raspberry Pi.

L’exemple de script python ci-dessous filtre sur la classe TPV, qui est le rapport Time Position Velocity, puis imprime les informations pertinentes.

#! /usr/bin/python

from gps import *
import time
   
gpsd = gps(mode=WATCH_ENABLE|WATCH_NEWSTYLE) 
print 'latitudetlongitudettime utctttaltitudetepvtepttspeedtclimb"https://www.raspberryme.com/using-python-with-a-gps-receiver-on-a-raspberry-pi/#"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'),"tt",
			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."

Ce script python filtre sur la classe SKY et imprime les informations satellites.




#! /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 'nn'
			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."


Le script python ci-dessous montre comment accéder aux données GPS en se connectant directement à l’interface série.
Il filtre sur $GPRMC NMEA phrases, puis divise les attributs bien connus en différentes 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)


Le script python ci-dessous montre comment accéder aux données GPS en se connectant directement à l’interface série.
Il filtre sur $GPGGA NMEA phrases, puis utilise pynmea2 pour analyser les données.

Pynmea2 peut être installé avec ;

pi@raspberrypi ~ $ pip installer 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)
  • VK-162 G-Mouse USB Dongle GPS Module de Navigation Antenne GPS Externe Montage à Distance Récepteur GPS USB pour Raspberry Pi Support Google Earth Windows Linux Geekstory
  • Riloer Récepteur GPS USB Vk-162 Support à distance compatible avec Google Earth Raspberry Pi Linux Window WIshiot