Main Content


Read line of ASCII string data from serial port

Since R2019b



data = readline(device) reads ASCII data until the first occurrence of the terminator from the serial port connection and returns data as a string without the terminator. If the function is unable to return any data within the period specified by the Timeout property of device, it returns data as a 0-by-0 double []. The function suspends MATLAB® execution until the terminator is reached or a timeout occurs.


collapse all

Create a connection to a serial port device. In this example, the serial port at COM3 is connected to a loopback device.

device = serialport("COM3",9600)
device = 

  Serialport with properties:

                 Port: "COM3"
             BaudRate: 9600
    NumBytesAvailable: 0

  Show all properties, functions

Check the default ASCII terminator.

ans = 


Set the terminator to "CR" and write a string of ASCII data. The writeline function automatically appends the terminator to the data.


Write another string of ASCII data with the terminator automatically appended.


Since the port is connected to a loopback device, the data you write to the device is returned to MATLAB. Read a string of ASCII data. The readline function returns data until it reaches a terminator.

ans = 


Read a string of ASCII data again to return the second string that you wrote.

ans = 


Clear the serial port connection.

clear device

Input Arguments

collapse all

Serial port connection, specified as a serialport object.

Example: readline(device) reads ASCII data from the serial port connection device.

Version History

Introduced in R2019b