pythonraspberry-piraspberry-pi3raspberry-pi2raspberry-pi4

serial.serialutil.SerialException: read failed


I'm doing a project with a Ublox NEO 6m gps and a Raspberry Pi 4 model B and I'm stuck on the following error:

  File "gps3.py", line 23, in <module>
    newdata=ser.readline()
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 509, in read
    raise SerialException('read failed: {}'.format(e))
serial.serialutil.SerialException: read failed: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
^CException ignored in: <module 'threading' from '/usr/lib/python3.7/threading.py'>

I found a lot of similar question but I haven't found a good answer yet. This is my Python code:

import time
import string
import pynmea2
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
from pubnub.exceptions import PubNubException

pnChannel = "raspi-tracker";

pnconfig = PNConfiguration()
pnconfig.ssl = False

pubnub = PubNub(pnconfig)
pubnub.subscribe().channels(pnChannel).execute()

while True:
    port="/dev/ttyAMA0"
    ser=serial.Serial(port, baudrate=9600, timeout=0.5)
    dataout = pynmea2.NMEAStreamReader()
    newdata=ser.readline()

    if newdata[0:6] == "$GPRMC":
        newmsg=pynmea2.parse(newdata)
        lat=newmsg.latitude
        lng=newmsg.longitude
        try:
            envelope = pubnub.publish().channel(pnChannel).message({
            'lat':lat,
            'lng':lng
            }).sync()
            print("publish timetoken: %d" % envelope.result.timetoken)
        except PubNubException as e:
            handle_exception(e)

I don't know if this is relevant information but I connected my Pi through WiFi.


Solution

  • I'm assuming this is due to your code re-initializing the connection each loop. I recommend trying the following code instead --

    port = "/dev/ttyAMA0"
    ser = serial.Serial(port, baudrate=9600, timeout=0.5)
    
    while True:
        newdata = ser.readline()
        if newdata[0:6] == "$GPRMC":
            # rest of your code