![](/img/trans.png)
[英]IndexError on Raspberry pi 3b+ but not in pc Python
[英]Trying to write and read via serial to a GPS module on Raspberry Pi 3b+ without any success
我正在嘗試使用 Raspberry Pi 3B+ 向 SIM808 GPS 模塊寫入和讀取命令。 開啟模塊的 AT 指令為AT+CGPSPWR=1
。 這是我的 python 代碼(我是一個完整的 python 菜鳥),
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
在SO上一段時間后,我嘗試了這個,
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
我錯過了什么?
原來我需要將字符串轉換為字節。 我就是這樣做的,這很有效,
ser.write(bytes("AT+CGPSPWR=1\n", 'utf-8')) #turn on the GPS module
rx = ser.readline()
print (rx.decode('utf-8'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.