serial.serialutil.SerialException: 读取失败

serial.serialutil.SerialException: read failed

我正在用 Ublox NEO 6m gps 和 Raspberry Pi 4 model B 做一个项目,但我遇到了以下错误:

  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'>

我发现了很多类似的问题,但我还没有找到一个好的答案。这是我的 Python 代码:

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)

我不知道这是否是相关信息,但我通过 WiFi 连接了我的 Pi。

我假设这是因为您的代码在每个循环中都重新初始化了连接。我建议改为尝试以下代码 --

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