Description

Called at the end of loop() when data is available. Use Serial.read() to capture this data.

Please note: most modern boards do not support this method. See "Notes and Warnings" further below this article.

Syntax

Use the following function to do something each loop cycle if there is still serial data available.

void serialEvent() {
  //statements
}

The Mega 2560 Rev3 and Due boards have additional serial ports which can be accessed by adding the corresponding number at the end of the function.

void serialEvent1() {
  //statements
}

void serialEvent2() {
  //statements
}

void serialEvent3() {
  //statements
}

Parameters

This function doesn't admit parameters.

Returns

The function returns nothing.

Example Code

An example showcasing the use of serialEvent.

String inputString = "";
bool stringComplete = false;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println("Type something and press Enter:");
}

void loop() {
  if (stringComplete) {
    Serial.print("You entered: ");
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
}

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

Notes and Warnings

Please note that serialEvent() does not work on any modern Arduino boards. The only recognized boards to have support as of 2023/12/06 are the UNO R3, Nano, Mega 2560 Rev3 and Due.

Instead, you can use the available() method. Examples in this page demonstrates how to read serial data only when it is available, similarly to how Serial.event() is implemented.

See also