Johnny5C
Posts: 82
Joined: Thu Apr 18, 2013 3:32 pm

Parsing NMEA strings with pynmea2

Sat Apr 02, 2016 9:24 pm

Hi forum folk.

I have hooked up a microstack GPS receiver to my B+, and can see the NMEA data using cat /dev/ttyAMA0, so the connections are OK . I found the parsing example below and the next step was to adapt it to my means, but it does not run.

Code: Select all

import serial
import pynmea2

def parseGPS(str):
    if str.find('GGA') > 0:
        msg = pynmea2.parse(str)
        print "Timestamp: %s -- Lat: %s %s -- Lon: %s %s -- Altitude: %s %s" % (msg.timestamp,msg.lat,msg.lat_dir,msg.lon,m$

serialPort = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5)

while True:
    str = serialPort.readline()
    parseGPS(str)

File "app2.py", line 7
print "Timestamp: %s -- Lat: %s %s -- Lon: %s %s -- Altitude: %s %s" % (msg.timestamp,msg.lat,msg.lat_dir,msg.lon,msg.lon_dir,msg.altitude,msg.altitude_units)
^
SyntaxError: invalid syntax

I have done a fair but of reading, but I cant see any obvious syntax issues?

Any help would be appreciated.

scotty101
Posts: 3649
Joined: Fri Jun 08, 2012 6:03 pm

Re: Parsing NMEA strings with pynmea2

Sat Apr 02, 2016 9:54 pm

Which version of python are you using?

In Python 3 print is a function e.g.
print("hello") not print "Hello"
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

DirkS
Posts: 9876
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: Parsing NMEA strings with pynmea2

Sat Apr 02, 2016 9:56 pm

Code: Select all

File "app2.py", line 7
    print "Timestamp: %s -- Lat: %s %s -- Lon: %s %s -- Altitude: %s %s" % (msg.timestamp,msg.lat,msg.lat_dir,msg.lon,msg.lon_dir,msg.altitude,msg.altitude_units)
                                                                       ^
SyntaxError: invalid syntax
The position of the caret is relevant. I would say the problem is in the format string.
Looking at https://github.com/Knio/pynmea2 my first suspect would be the formatting of the first parameter.
Apparently it's not a string, but a datetime variable.
I'm not sure if you can use date format parameters with % formatting. Maybe you have to convert it to a string first

I think 'format' is more flexible than '%' (see e.g. https://pyformat.info/ or https://docs.python.org/2/library/strin ... ing-syntax)

Johnny5C
Posts: 82
Joined: Thu Apr 18, 2013 3:32 pm

Re: Parsing NMEA strings with pynmea2

Sun Apr 03, 2016 12:29 pm

Thanks for the quick replies. I have a few things to try now.

For info I'm running a fresh install of Jessie on a B+

And, when launching the python script it with sudo python script.py it cant import serial. I tried with python3 and it gets as far as the error above, and it then i got stuck.

**On edit, it appears its tripping over import serial, so is there something different in Jessie?**

Cheers

Return to “Python”