This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

fgets (serial)

Read line of text from device and include terminator


tline = fgets(obj)
[tline,count] = fgets(obj)
[tline,count,msg] = fgets(obj)


tline = fgets(obj) reads one line of text from the device connected to the serial port object, obj, and returns the data to tline. This returned data includes the terminator with the text line. To exclude the terminator, use fgetl.

[tline,count] = fgets(obj) returns the number of values read to count, including the terminator.

[tline,count,msg] = fgets(obj) returns a warning message to msg if the read operation was unsuccessful.


Create the serial port object s, connect s to a Tektronix® TDS 210 oscilloscope, and write the RS232? command with the fprintf function. RS232? instructs the scope to return serial port communications settings.

s = serial('COM1');

Because the default value for the ReadAsyncMode property is continuous, data is automatically returned to the input buffer.

ans =

Use fgets to read the data returned from the previous write operation, and include the terminator.

settings = fgets(s)
settings =
ans =

Disconnect s from the scope, and remove s from memory and the workspace.

clear s

More About

collapse all


Before you can read text from the device, it must be connected to obj with the fopenfunction. A connected serial port object has a Status property value of open. An error is returned if you attempt to perform a read operation while obj is not connected to the device.

If msg is not included as an output argument and the read operation was not successful, then a warning message is returned to the command line.

The ValuesReceived property value is increased by the number of values read – including the terminator – each time fgets is issued.

    Note:   You cannot use ASCII values larger than 127 characters. The function is limited to 127 binary characters.

Rules for Completing a Read Operation with fgets

A read operation with fgets blocks access to the MATLAB® command line until:

  • The terminator specified by the Terminator property is reached.

  • The time specified by the Timeout property passes.

  • The input buffer is filled.

    Note:   You cannot use ASCII values larger than 127 characters. The function is limited to 127 binary characters.

Introduced before R2006a

Was this topic helpful?