Djent
Djent

Reputation: 3467

Reading data from serial in python

I got GPS module who returns NMEA data. When I'm trying to print all data it returns using following code, I'm getting this.

while True:
try:
    rcv = port.read()
    print rcv

Then, I've made some modification that will read NMEA data cleaner. It looks like this:

port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=10.0)

line = []
print("connected to: " + port.portstr)

while True:
    try:
        rcv = port.read()
    except:
        rcv = ''


    line.append(rcv)

    if rcv == '\n':
        line = "".join(line)        
        print line
        line = []

Output looks like that:

$GPGGA,183345.000,5023.3424,N,01857.3817,E,1,7,1.25,313.3,M,42.1,M,,*53

$GPGSA,A,3,09,26,28,08,15,18,17,,,,,,1.52,1.25,0.88*06

$GPRMC,183345.000,A,5023.3424,N,01857.3817,E,0.40,55.07,050214,,,A*54

$GPVTG,55.07,T,,M,0.40,N,0.74,K,A*0D

$GPGGA,183346.000,5023.3423,N,01857.3817,E,1,7,1.25,313.3,M,42.1,M,,*57

$GPGSA,A,3,09,26,28,08,15,18,17,,,,,,1.52,1.25,0.88*06

The problem is that sometimes it misses some commas or other data, and NMEA parser is reading it wrong. Is there any better and cleaner way to read whole NMEA frames via serial?

Upvotes: 2

Views: 5133

Answers (1)

chk
chk

Reputation: 308

you can use readline instead of read, That will continue to read characters until an EOL is received.

Upvotes: 5

Related Questions