Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By Nicholas8266
#93832 I'm trying to build a serial command line interface for an ESP8266. Here's some of my code:

Code: Select allString ReadUntilEnter(String currentInput) {
    if (Serial.available() > 0) {
        char inputChar = Serial.read();

        // On newline, stop reading chars and return the string
        if ((int) inputChar == 13) {
            Serial.print("\r\n");
            return currentInput;
        }
        // If the character is not a newline, add it to the string and keep listening
        else {
            Serial.print(inputChar);
            currentInput += inputChar;
            return ReadUntilEnter(currentInput);
        }
    }
    // Wait for serial to become available
    else {
        delay(100);
        return ReadUntilEnter(currentInput);
    }
}

void loop() {
    Serial.print("Console# ");
    while (Serial.available() == 0) {}
    String command = ReadUntilEnter("");
    // handle command
}


Essentially, I want the users to be greeted with a prompt that says:
Console#
The user can then type in a command:
Console# hack cia
The issue I am encountering happens when the user has typed one or more characters inside the prompt, but has not yet hit enter. The function is holding up the thread while waiting for the next character. The watchdog does not like this and will reset the ESP if someone takes too long to type a command. It works decently well with the 100 ms delay but if you take a long time, it will be halted by the watchdog. I have tried using the yield() function in place of the 100 ms delay, but the ESP would crash once it hit the yield statement - not a watchdog stop but a full crash with a stack trace and everything. Can someone please give me some advice on how to get this to work properly? I have looked at a ton of threads on this and other forums regarding the watchdog but I can't get it quite right.

Thanks so much
User avatar
By Inq720
#93844 Sounds like your resurrecting a 1980's DOS machine or worse yet a TTY terminal. Actually, the ESP8266 is way overkill for that duty. :D It could run circles around my first IBM PC.

I've used Web UIs for input to ESP8266 for at least five years, so my Serial usage may be out of date. Unless your concept must use this blocking kind of input, you might want to consider a more asynchronous input method instead of blocking/trying to yield until user is done, then proceeding. I had to dumpster dive my disk, but I found this snippet...

Arduino version follows...

Code: Select allvoid loop()
{
    if (!Serial.available())
        return;

    static String cmd = "";
    char c = Serial.read();
    if (c == '\n')
    {
        callYourFunction(cmd);
        cmd = "";   // Reset it ready for next input line.
    }
    else
        cmd += c;
}