Serial.available()

Description

Get the number of bytes (characters) available for reading from the serial port. This refers to data that has already been received and is currently stored in the serial receive buffer (which holds 64 bytes).

Serial.available()
inherits from the Stream utility class.

Syntax

Use the following function to get the number of available bytes in the input serial buffer:

Serial.available()

Parameters

The function admits the following object:

Serial
: serial port object. See the list of available serial ports for each board on the Serial main page.

Returns

The function returns the number of bytes available to read.

Example Code

The following code returns a character received through the serial port.

1int incomingByte = 0; // for incoming serial data
2
3void setup() {
4 Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
5}
6
7void loop() {
8 // reply only when you receive data:
9 if (Serial.available() > 0) {
10 // read the incoming byte:
11 incomingByte = Serial.read();
12
13 // say what you got:
14 Serial.print("I received: ");
15 Serial.println(incomingByte, DEC);
16 }
17}

Multiple serial example: This code sends data received in one serial port of the Arduino board to another. This can be used, for example, to connect a serial device to the computer through the Arduino board.

1void setup() {
2 Serial.begin(9600);
3 Serial1.begin(9600);
4}
5
6void loop() {
7 // read from port 0, send to port 1:
8 if (Serial.available()) {
9 int inByte = Serial.read();
10 Serial1.print(inByte, DEC);
11 }
12 // read from port 1, send to port 0:
13 if (Serial1.available()) {
14 int inByte = Serial1.read();
15 Serial.print(inByte, DEC);
16 }
17}

See also

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.