I've trying to send AT commands via pySerial to a SIM800 module. The problem I'm having is that when I send a command, the message I receive back is the output of the previous command (or sometimes, the previous command itself). My code looks like this:
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
I feel it's something to do with needing to flush buffers, but I'm not too experienced with Serial work. Can anyone suggest what I'm doing wrong?