1

am trying to write a code that well read data from my serial UART and parse the NMEA gps sentence by using pynmea2 module i was running this code in python 2 and it worked like magic ,when i tried to run it with python3 a type error rise am using python idle to write the code in my raspberry pi 3 and all the hardware between neo 6m gps and the raspberry are fine my code is blow `

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,msg.lon_dir,msg.altitude,msg.altitude_units)

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

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

`

and i get this Messag

 "if str.find('GGA').0:
    TypeError:'a bytes-like object is required, not 'str' "
  • Possible duplicate of [TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3](https://stackoverflow.com/questions/33054527/typeerror-a-bytes-like-object-is-required-not-str-when-writing-to-a-file-in) – Anton Gorbunov Feb 12 '19 at 19:08

1 Answers1

2

In Python 3.x, text is always Unicode and is represented by the str type, and binary data is represented by the bytes type. serial.readline() in fact returns binary data, and therefor in bytes type. This is different from Python 2.x.

You can convert the encoded bytes data into str with:

str = serailPort.readline().decode()
hcheung
  • 3,377
  • 3
  • 11
  • 23
  • You are welcome. I've been to the situation long time ago. Please accept it as answer by clicking on the check mark beside this post. Thanks. – hcheung Feb 13 '19 at 11:51