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

Moderator: igrr

User avatar
By Mmiscool
#25388 Hello,

I have been atempting to create a function that will listen for serial input and then compare that input against a list of commands.

It seems to work but it keeps looping and presenting the prompt.

Am i missing some thing?

Code: Select allvoid loop()
{     
  String CommandToRun;
  CommandToRun = getSerialInput();
  if (CommandToRun == "run")
  {
    Serial.println("Command received\n");
  }
     
}



String  getSerialInput()
{
  Serial.println("\n>");

  String someInput;
  while (Serial.available() > 0)
  {
    delay(10);
   
    char recieved = Serial.read();
    // Process message when new line character is recieved
    if (recieved == '\n')
    {
      Serial.println(someInput);
      return someInput;
    }
    someInput += recieved;
  }
}
User avatar
By kolban
#25395 Howdy,
I think you have a logic error in your code.

Follow the path in your function called "getSerialInput()" when there is no input. i.e. when Serial.available() returns 0. Your function will return (with no output) and then loop() will end and then restart and you will again call "getSerialInput()" ....
User avatar
By martinayotte
#25403 As Kolban mentioned, the logic isn't good in your code.

Here is a snippet of code (not showing the whole sketch) :

Code: Select allvoid loop()
{
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial.write(inByte);
    buf[i] = (char)inByte;
    if (inByte == '\r' or inByte == '\n') {
      buf[i] = 0;
      i = 0;
      Serial.print("echo = ");
      Serial.println(buf);
      if (strcmp(buf, "hello") == 0) {
        Serial.println("Hello !");
      }
      else if (strcmp(buf, "showip") == 0) {
        showIP(Serial);
      }
    }
    else
      i++;
  }
}


If you wish to get the whole sketch, search in my past posts, I've sent Sketch_Buffet.zip, which also handle other stuff like I2C.
User avatar
By Mmiscool
#25409 Thanks.

That helped a lot.

My function is now.

Code: Select allString  getSerialInput()
{
  byte donereceivinginfo = 0;
  //indicates a prompt to user
  Serial.println(">");

  String someInput;
  while (donereceivinginfo == 0)
  {
    delay(10);
    while (Serial.available() > 0)
    {
      char recieved = Serial.read();
      // Process message when new line character is recieved
      if (recieved == '\n')
      {
        Serial.print(someInput);
        donereceivinginfo = 1;
        return someInput;
      }
      someInput += recieved;
    }
  }
}