我试图通过 pySerial 向 SIM800 模块发送 AT 命令。我遇到的问题是,当我发送命令时,我收到的消息是上一个命令的输出(或者有时是上一个命令本身)。我的代码如下所示:
import time
import serial
ser = serial.Serial()
ser.port = "/dev/ttyAMA0"
ser.baudrate = 9600
ser.open()
def readData():
buffer = ""
while True:
oneByte = ser.read(1)
if oneByte == b"\n":
return buffer
else:
buffer += oneByte.decode("ascii")
def sendData(command, timeout):
fullcommand = "{}\r\n".format(command)
print "Sent: {}".format(fullcommand)
ser.write(fullcommand)
time.sleep(timeout)
return
sendData("AT", 1) # Expecting "OK" back
print "Return: {}".format(readData()) # Prints AT
sendData("AT+CIPSHUT", 5) # Expecting "SHUT OK" back
print "Return: {}".format(readData()) # Prints OK
sendData("AT+CIPMUX=0", 2) # Expecting "OK" back
print "Return: {}".format(readData()) # Prints AT+CIPSHUT
sendData("AT+CSTT=\"myapn\"", 4) # Expecting "OK" back
print "Return: {}".format(readData()) # Prints SHUT OK
我觉得这与需要刷新缓冲区有关,但我对串行工作没有太多经验。谁能建议我做错了什么?