我试图通过pySerial将AT命令发送到SIM800模块。我遇到的问题是,当我发送命令时,我收到的消息是前一个命令的输出(或者有时是前一个命令本身)。我的代码如下所示:
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
我觉得这与需要刷新缓冲区有关,但我对Serial工作没有太多经验。任何人都可以建议我做错了吗?
答案 0 :(得分:2)
通过UART与SIM 800通讯时,我遇到了同样的问题。我使用ATE0命令禁用了回显。尝试此操作可能会对您有所帮助。
import serial
import time
# dmesg | grep tty #to get which port it ts using
port = serial.Serial("/dev/ttyO2", baudrate=9600, timeout=1)
if port.isOpen():
print(port.name + ' is open...!!!')
# Transmitting AT Commands to the Modem
port.write('AT'+'\r')
print port.read(32)
time.sleep(2)
# To disable echo
port.write('ATE0'+'\r')
print port.read(32)
time.sleep(2)
答案 1 :(得分:0)
一些事情。
如果要设置写入超时,则需要在write_timeout
对象的初始化或设置Serial
如果您真的担心数据仍然在输入缓冲区中,您可以ser.reset_input_buffer()
如果您真的担心数据仍然在输出缓冲区中,您可以执行ser.reset_output_buffer()
现在在代码方面你可以做这样的事情
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)
ser.write_timeout = timeout # This is where you can set the timeout
bytes_written = ser.write(fullcommand)
# Check to see if all the data was written
if bytes_written == len(fullcommand):
print "Sent: {}".format(fullcommand)
else:
print 'Not all data transferred'
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