-->
Page 1 of 2

Problem attempting to create serial input function

PostPosted: Sat Aug 08, 2015 5:51 pm
by Mmiscool
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;
  }
}

Re: Problem attempting to create serial input function

PostPosted: Sat Aug 08, 2015 6:53 pm
by kolban
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()" ....

Re: Problem attempting to create serial input function

PostPosted: Sat Aug 08, 2015 8:09 pm
by martinayotte
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.

Re: Problem attempting to create serial input function

PostPosted: Sat Aug 08, 2015 9:16 pm
by Mmiscool
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;
    }
  }
}