尝试通过串行方式写入和读取Raspberry Pi 3b+上的GPS模块,但未成功

2024-10-03 17:16:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Raspberry Pi 3B+向SIM808 GPS模块写入命令并从中读取命令。打开模块的AT命令是AT+CGPSPWR=1。这是我的python代码(我是一个完整的python noob)

from time import sleep
import serial

ser = serial.Serial(
    port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=2.0
)

print(ser.name) # check which port was really used
ser.write(b'AT+CGPSPWR=1'+'\r\n') #turn on the GPS module
sleep(2)
ser.write(b'AT+CGPSOUT=2'+'\r\n') #set the module to output GGA sentence every 1 second
state = ser.readline()
print (state)

有了这个,我得到了以下错误

/dev/ttyS0
Traceback (most recent call last):
  File "gps-sim808-test.py", line 14, in <module>
    ser.write(b'AT+CGPSPWR=1'+'\r\n') #turn on the GPS module
TypeError: can't concat str to bytes

过了一会儿,我试了一下

ser.write(('AT+CGPSPWR=1'+'\r\n').encode) #turn on the GPS module并获得此错误

/dev/ttyS0
Traceback (most recent call last):
  File "gps-sim808-test.py", line 14, in <module>
    ser.write(('AT+CGPSPWR=1'+'\r\n').encode) #turn on the GPS module
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 532, in write
    d = to_bytes(data)
  File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 66, in to_bytes
    return bytes(bytearray(seq))
TypeError: 'builtin_function_or_method' object is not iterable

我错过了什么


Tags: thetopyonlineserialatser
1条回答
网友
1楼 · 发布于 2024-10-03 17:16:24

结果是我需要将字符串转换为字节。我就是这样做的,这很有效

ser.write(bytes("AT+CGPSPWR=1\n", 'utf-8')) #turn on the GPS module
rx = ser.readline()
print (rx.decode('utf-8'))

相关问题 更多 >