Description

Get the number of bytes (characters) available for writing in the serial buffer without blocking the write operation.

Syntax

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

Serial.availableForWrite()

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 write.

Example Code

The following code checks if there is enough space in the serial buffer to write.

void setup() {
  Serial.begin(9600); // Start serial communication at 9600 baud
  while (!Serial);    // Wait for serial port to be ready 
}

void loop() {
  int bytesAvailable = Serial.availableForWrite(); // Check how many bytes we can write

  Serial.print("Bytes available to write: ");
  Serial.println(bytesAvailable);

  if (bytesAvailable > 13) {
    Serial.println("Hello, world!"); // Send a message only if enough buffer space is available
  }

  delay(1000); // Wait a second before checking again
}

Notes and Warnings

If you are using a software-implemented UART, the function will return 0. It will only return the available bytes in HardwareSerial.

See also