SerialEvent

Hi I have a question about the example SerialEvent function. Can someone help me please? Thanks!

So I wonder how does the serialEvent function and loop function work. Do they run alternatively? Or do they run simultaneously?

Thanks!

JackZ:
So I wonder how does the serialEvent function and loop function work. Do they run alternatively? Or do they run simultaneously?

Just look up the source code of Arduinos main() function:

int main(void)
{
    init();
#if defined(USBCON)
    USBDevice.attach();
#endif
    setup();
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

So each time the loop() function is finished, the main() function will call the event handler if any event handler is defined, before restarting the loop() function again.

serialEvent behaves exactly the same as if you had code like this

void loop() {
    // other stuff
    if (Serial.available() > 0) {
       serialEvent();
    }
}

I can't think of any good reason for using serialEvent(). I think it was included to achieve some commonality with code written in the Processing language.

You may find some useful stuff in serial input basics

...R