pyserial sim800/900在命令中 - 读取缓冲区包含以前的写缓冲区数据



我尝试通过pyserial在命令上发送到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 = "{}rn".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

我觉得这与需要冲洗缓冲液有关,但是我对连续作品的经验不太经验。谁能建议我做错了什么?

我在通过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. 如果要设置写入超时,则需要在Serial对象的初始化或设置ser.write_timeout

  2. 中使用write_timeout完成。
  3. 如果您真的担心数据仍在输入缓冲区中,则可以执行ser.reset_input_buffer()

  4. 如果您真的担心数据仍在输出缓冲区中,则可以执行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 = "{}rn".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

相关内容

  • 没有找到相关文章

最新更新