Serial event not working

Hi all,
I am trying to use serial event to detect a message and subsequently run a function. However the serial event structure i am using does not seem to work. The code will not register messages I send via the serial monitor.

String inputString = "";
boolean stringComplete = false;

void setup()
{
Serial.begin(9600);
inputString.reserve(200);

}

void loop()
{
if(stringComplete)
{
if(inputString.equals("scan"))
{
Serial.println("scan");
}
}
}

void serialEvent()
{
while (Serial.available())
{
char inChar = (char)Serial.read();
inputString += inChar;
if (inChar == '\n')
{
stringComplete = true;
}
}
}

Thanks :slight_smile:

Have you tried printing inputString inside the serialEvent function ?

As a matter of interest where do you rest stringComplete to false again ?

I have tried printing inputString and it prints correctly, but for some reason the message is not received by the if statement. Sorry this was an example code I made for the forum, I reset stringcomplete after the print :slight_smile:

You should either test for the CR/LF at the line end, or not add it to the string.

String inputString = "";
boolean stringComplete = false;

void setup()
{
  Serial.begin(9600);
  inputString.reserve(200);

}

void loop()
{
  if (stringComplete)
  {
    if (inputString.equals("scan"))
    {
      Serial.println("scan");
    }
    stringComplete = false;
    inputString = "";
  }
}

void serialEvent()
{
  while (Serial.available())
  {
    char inChar = (char)Serial.read();
    if (inChar != '\n'  && inChar != '\r') {
      inputString += inChar;
    }
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R

Thank you Whandall, that has fixed my problem!

I would advise against using String in general (on 8 bit AVRs) and there is no reason to use serialEvent at all.

Just put its code into loop, controlled by if (Serial.available()) {.

I have tried printing inputString and it prints correctly,

When printing values that are tested within the code it is helpful to print a marker, such as “>” before the data and another one, perhaps “<” after it. This allows you to identify whether the data has invisible characters as part of it which was the case here.

By the way, using serialEvent() has always seemed to me to be a waste of time. When using it the Serial port is only checked once for each iteration of the loop() function so why not do it yourself ? Unfortunately the name of the function implies that it is interrupt driven and that it will be called whenever Serial data is available, which is not the case.