AT command responses (understanding order of code execution on Arduino)

后端 未结 2 789
别跟我提以往
别跟我提以往 2020-12-11 12:05

I\'m sending AT commands to an ESP8266 from an Arduino Uno/Nano (ATmega328) and attempting to parse the end of the strings received in response to establish how the ESP reac

相关标签:
2条回答
  • 2020-12-11 12:13

    Your if after the while is indeed wrong because you might have read more stuff back and thus you don't end with the target string even though "ok" was received.

    You should just test if responseBuffer ends with target and return true only when you receive a new character in the while loop and not after. After you have a timeout, just return false.

    0 讨论(0)
  • 2020-12-11 12:19

    Any idea why it returns before the full response is received (well within the timeout period)?

    Yes, your main problem is the following

    if (ESP.available())
    

    This makes the waitForResponse function return whenever the UART (or some other serial IO buffer) is empty - which is not what you want. What you want is to read from the serial port until you have received a line terminated with "\r\n".

    Is it something to do with the endsWith() function?

    Yes, that is an additional problem combined with ESP.available because you are attempting to match the end of a response line from the modem with what ever random data chopping occurs in the serial path. If you are extremely lucky this will be on line boundaries, but most likely not and you should not rely on that.

    This is a general protocol problem known as framing that applies to any kind of asynchronous serial communication. For modem communications the framing characters are \r and \n.

    Do yourself a favour and implement a readline function that reads one by one character until it the previous character was \r and the current character is \n and then return everything it read so far.

    Then use that function exclusively1 for reading modem response data. This applies both to Intermediate result codes like CONNECT as well as Final result codes (e.g. OK etc). "Parsing" the response lines can then be as simple as

    if (responseLine.equals("CONNECT\r\n")) ...
    

    or

    if (isFinalResultCode(responseLine)) ...
    

    As I said before, the only correct way to process modem output is to divide the output into complete lines and iterate one full line at the time.


    1 The only exception is when parsing AT+CMGS response data.

    0 讨论(0)
提交回复
热议问题