3

I have come across several examples about serialEvent() function, which look like this:

void serialEvent(){
  if(Serial.available()){
    \\do something 
  }
}

The serialEvent() function is called when data is available, so which is the necessity of the if (or while) structure since that would be always true?

(In several cases I have excluded the if structure, and the code works fine)

2 Answers 2

7

As far as I understand, using an if statement wouldn't make any difference, but using a while statement would.

The serialEvent() function is executed within each execution of your loop() function if there is data available, so it would be something like:

while (true) 
{
    loop();
    if(data_available)
        serialEvent();
}

If you only have one byte of information in the buffer, then you wouldn't have any problem at all.

But if you want to read multiple bytes at the same time, you would have to wait until the loop() is executed again to read the next byte.

You will solve that problem if you write your serialEvent() like this:

void serialEvent()
{
    while (Serial.available())
    {
        // do something
    }
}

That way, you will read all the information available at once and then return to the loop.

1

It's a burdon how incomplete and hidden a lot of things are in the IDE of Arduino.

It took me five hours to discover how the serialEvent() function works for other ports (as serialEvent2() for the serial-port #2.

It's the same with how the function itself works. I still don't know... As an example just insert a delay in the above answer and it proves that: "That way, you will read all the information available at once and then return to the loop." is NOT true.

void serialEvent()
  {
    while (Serial.available())
      {
        // do something
      }
    delay(1000);
  }
1
  • don't use serialEvent it has no advantage over if (Serial.available()) in loop()
    – Juraj
    May 6, 2019 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.