Main Content

serial

(To be removed) Create serial port object

    serial will be removed in a future release. Use serialport instead. For more information on updating your code, see Compatibility Considerations

    Description

    A serial object represents a connection to a serial port.

    Creation

    Description

    example

    obj = serial('port') creates a serial port object associated with the serial port specified by port. If port does not exist, or if it is in use, you will not be able to connect the serial port object to the instrument with the fopen function.

    example

    obj = serial('port',Name,Value) specifies options using one or more name-value arguments in addition to the input arguments in previous syntax. If an invalid property name or property value is specified, an error is returned and the serial port object is not created.

    Properties

    expand all

    Common Properties for All Interface Objects

    Byte order of instrument, specified as littleEndian or bigEndian. If ByteOrder is littleEndian, then the instrument stores the first byte in the first memory address. If ByteOrder is bigEndian, then the instrument stores the last byte in the first memory address.

    For example, suppose the hexadecimal value 4F52 is to be stored in instrument memory. Because this value consists of two bytes, 4F and 52, two memory locations are used. Using big-endian format, 4F is stored first in the lower storage address. Using little-endian format, 52 is stored first in the lower storage address.

    Note

    You should configure ByteOrder to the appropriate value for your instrument before performing a read or write operation. Refer to your instrument documentation for information about the order in which it stores bytes.

    You can set this property on interface objects such as TCP/IP or GPIB. In this example, a TCP/IP object, Tobj, is set to bigEndian by default, and you change it to littleEndian.

    Tobj.ByteOrder = 'littleEndian'

    The possible values are as follows.

    littleEndian

    The byte order of the instrument is little-endian.

    Default for serial, gpib, and visa objects.

    bigEndian

    The byte order of the instrument is big-endian.

    Default for tcpip and udp objects.

    Example

    This example shows how to set the byte order for a TCP/IP object. Create a TCP/IP object associated with the host 127.0.0.1 and port 4000. Change the byte order from the default of bigEndian to littleEndian.

    t = tcpip('127.0.0.1', 4000);
    t.ByteOrder = 'littleEndian';
    

    This property is read-only.

    Number of bytes currently available to be read from the input buffer. The property value is continuously updated as the input buffer is filled, and is set to 0 after the fopen function is issued.

    You can make use of BytesAvailable only when reading data asynchronously. This is because when reading data synchronously, control is returned to the MATLAB® Command Window only after the input buffer is empty. Therefore, the BytesAvailable value is always 0.

    The BytesAvailable value can range from zero to the size of the input buffer. Use the InputBufferSize property to specify the size of the input buffer. Use the ValuesReceived property to return the total number of values read.

    Callback function to execute when a bytes-available event occurs. A bytes-available event occurs when the number of bytes specified by the BytesAvailableFcnCount property is available in the input buffer, or after a terminator is read, as determined by the BytesAvailableFcnMode property.

    Note

    A bytes-available event can be generated only for asynchronous read operations.

    If the RecordStatus property value is on, and a bytes-available event occurs, the record file records this information:

    • The event type as BytesAvailable

    • The time the event occurred using the format day-month-year hour:minute:second:millisecond

    Note

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

    Example

    Create the serial port object s on a Windows® machine for a Tektronix® TDS 210 two-channel oscilloscope connected to the serial port COM1.

    s = serial('COM1');

    Configure s to execute the callback function instrcallback when 40 bytes are available in the input buffer.

    s.BytesAvailableFcnCount = 40;
    s.BytesAvailableFcnMode = 'byte';
    s.BytesAvailableFcn = @instrcallback;

    Connect s to the oscilloscope.

    fopen(s)

    Write the *IDN? command, which instructs the scope to return identification information. Because the default value for the ReadAsyncMode property is continuous, data is read as soon as it is available from the instrument.

    fprintf(s,'*IDN?')

    The resulting output from instrcallback is shown below.

    BytesAvailable event occurred at 18:33:35 for the object: 
    Serial-COM1.

    56 bytes are read and instrcallback is called once. The resulting display is shown above.

    s.BytesAvailable
    ans =
        56

    Suppose you remove 25 bytes from the input buffer and issue the MEASUREMENT? command, which instructs the scope to return its measurement settings.

    out = fscanf(s,'%c',25);
    fprintf(s,'MEASUREMENT?')

    The resulting output from instrcallback is shown below.

    BytesAvailable event occurred at 18:33:48 for the object: 
    Serial-COM1.
    
    BytesAvailable event occurred at 18:33:48 for the object: 
    Serial-COM1.

    There are now 102 bytes in the input buffer, 31 of which are left over from the *IDN? command. instrcallback is called twice; once when 40 bytes are available and once when 80 bytes are available.

    s.BytesAvailable
    ans =
        102

    This property is read-only.

    Number of bytes that must be available in the input buffer before a bytes-available event is generated.

    Use the BytesAvailableFcnMode property to specify whether the bytes-available event occurs after a certain number of bytes are available or after a terminator is read.

    The bytes-available event executes the callback function specified for the BytesAvailableFcn property.

    You can configure BytesAvailableFcnCount only when the object is disconnected from the instrument. You disconnect an object with the fclose function. A disconnected object has a Status property value of closed.

    This property is read-only.

    For serial port, TCPIP, UDP, or VISA-serial objects, you can configure BytesAvailableFcnMode to be terminator or byte. For all other instrument objects, you can configure BytesAvailableFcnMode to be eosCharCode or byte.

    If BytesAvailableFcnMode is terminator, a bytes-available event occurs when the terminator specified by the Terminator property is read. If BytesAvailableFcnMode is eosCharCode, a bytes-available event occurs when the End-Of-String character specified by the EOSCharCode property is read. If BytesAvailableFcnMode is byte, a bytes-available event occurs when the number of bytes specified by the BytesAvailableFcnCount property is available.

    The bytes-available event executes the callback function specified for the BytesAvailableFcn property.

    You can configure BytesAvailableFcnMode only when the object is disconnected from the instrument. You disconnect an object with the fclose function. A disconnected object has a Status property value of closed.

    The possible values for Serial, TCPIP, UDP, and VISA-serial objects are as follows. The default value is enclosed in braces ({}).

    {terminator}

    A bytes-available event is generated when the terminator is reached.

    byte

    A bytes-available event is generated when the specified number of bytes available.

    The possible values for GPIB, VISA-GPIB, VISA-VXI, and VISA-GPIB-VXI objects are as follows. The default value is enclosed in braces ({}).

    {eosCharCode}

    A bytes-available event is generated when the EOS (End-Of-String) character is reached.

    byte

    A bytes-available event is generated when the specified number of bytes is available.

    This property is read-only.

    Number of bytes currently in the output buffer waiting to be written to the instrument. The property value is continuously updated as the output buffer is filled and emptied, and is set to 0 after the fopen function is issued.

    You can make use of BytesToOutput only when writing data asynchronously. This is because when writing data synchronously, control is returned to the MATLAB Command Window only after the output buffer is empty. Therefore, the BytesToOutput value is always 0.

    Use the ValuesSent property to return the total number of values written to the instrument.

    Note

    If you attempt to write out more data than can fit in the output buffer, then an error is returned and BytesToOutput is 0. You specify the size of the output buffer with the OutputBufferSize property.

    Callback function to execute when an error event occurs.

    Note

    An error event is generated only for asynchronous read and write operations.

    An error event is generated when a timeout occurs. A timeout occurs if a read or write operation does not successfully complete within the time specified by the Timeout property. An error event is not generated for configuration errors such as setting an invalid property value.

    If the RecordStatus property value is on, and an error event occurs, the record file records this information:

    • The event type as Error

    • The error message

    • The time the event occurred using the format day-month-year hour:minute:second:millisecond

    This property is read-only.

    Total number of bytes that can be stored in the software input buffer during a read operation.

    A read operation is terminated if the amount of data stored in the input buffer equals the InputBufferSize value. You can read text data with the fgetl, fgets, or fscanf functions. You can read binary data with the fread function.

    You can configure InputBufferSize only when the instrument object is disconnected from the instrument. You disconnect an object with the fclose function. A disconnected object has a Status property value of closed.

    If you configure InputBufferSize while there is data in the input buffer, then that data is flushed.

    Example

    This example shows how to set the input buffer size for a serial port object. The InputBufferSize property specifies the total number of bytes that can be stored in the software input buffer during a read operation. By default, InputBufferSize is 512 bytes. There could be a case when you would want to increase it to higher than the default size.

    Create a serial port object associated with the COM1 port. Set the input buffer size to 768 bytes.

    s = serial('COM1');
    s.InputBufferSize = 768;
    

    Descriptive name for an instrument object.

    When you create an instrument object, a descriptive name is automatically generated and stored in Name. However, you can change this value at any time. As shown below, the components of Name reflect the instrument object type and the input arguments you supply to the creation function.

    Instrument Object

    Default Value of Name

    GPIB

    GPIB and BoardIndex-PrimaryAddress-SecondaryAddress

    Serial Port

    Serial and Port

    TCPIP

    TCPIP and RemoteHost

    UDP

    UDP and RemoteHost

    VISA-serial

    VISA-Serial and Port

    VISA-GPIB

    VISA-GPIB and BoardIndex-PrimaryAddress-SecondaryAddress

    VISA-VXI

    VISA-VXI and ChassisIndex-LogicalAddress

    VISA-GPIB-VXI

    VISA-GPIB-VXI and ChassisIndex-LogicalAddress

    VISA-TCPIP

    VISA-TCPIP and BoardIndex-RemoteHost-LANName

    VISA-RSIB

    VISA-RSIB and RemoteHost

    VISA-USB

    VISA-USB and BoardIndex-ManufacturerID- ModelCode-SerialNumber-InterfaceIndex

    If the secondary address is not specified when a GPIB or VISA-GPIB object is created, then Name does not include this component.

    If you change the value of any property that is a component of Name (for example, Port or PrimaryAddress), then Name is automatically updated to reflect those changes.

    Way for application developers to prevent end-user access to the instrument objects created by their application. When an object's ObjectVisibility property is set to off, instrfind and instrreset do not return or delete those objects.

    Objects that are not visible are still valid. If you have access to the object (for example, from within the file that creates it), then you can set and get its properties and pass it to any function that operates on instrument objects.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {on}

    Object is visible to instrfind and instrreset

    off

    Object is not visible from the command line (except by instrfindall)

    Example

    The following statement creates an instrument object with its ObjectVisibility property set to off.

    g = gpib('mcc',0,2,'ObjectVisibility','off');
    instrfind
    ans =
         []

    However, since the object is in the workspace (g), you can access it.

    g.ObjectVisibility
    
    ans =
    
    	off

    This property is read-only.

    Total number of bytes that can be stored in the software output buffer during a write operation.

    An error occurs if the output buffer cannot hold all the data to be written. You write text data with the fprintf function. You write binary data with the fwrite function.

    You can configure OutputBufferSize only when the instrument object is disconnected from the instrument. You disconnect an object with the fclose function. A disconnected object has a Status property value of closed.

    Example

    This example shows how to set the output buffer size for a serial port object. The OutputBufferSize property specifies the maximum number of bytes that can be written to the instrument at once. By default, OutputBufferSize is 512 bytes. There could be a case when you would want to limit it to less than the default size.

    Create a serial port object associated with the COM1 port. Set the output buffer size to 256 bytes.

    s = serial('COM1');
    s.OutputBufferSize = 256;
    

    Callback function to execute when an output-empty event occurs. An output-empty event is generated when the last byte is sent from the output buffer to the instrument.

    Note

    An output-empty event can be generated only for asynchronous write operations.

    If the RecordStatus property value is on, and an output-empty event occurs, the record file records this information:

    • The event type as OutputEmpty

    • The time the event occurred using the format day-month-year hour:minute:second:millisecond

    You can configure ReadAsyncMode to be continuous or manual. If ReadAsyncMode is continuous, the object continuously queries the instrument to determine if data is available to be read. If data is available, it is automatically read and stored in the input buffer. If issued, the readasync function is ignored.

    If ReadAsyncMode is manual, the object will not query the instrument to determine if data is available to be read. Instead, you must manually issue the readasync function to perform an asynchronous read operation. Because readasync checks for the terminator, this function can be slow. To increase speed, you should configure ReadAsyncMode to continuous.

    Note

    If the instrument is ready to transmit data, then it will do so regardless of the ReadAsyncMode value. Therefore, if ReadAsyncMode is manual and a read operation is not in progress, then data can be lost. To guarantee that all transmitted data is stored in the input buffer, you should configure ReadAsyncMode to continuous.

    You can determine the amount of data available in the input buffer with the BytesAvailable property. For either ReadAsyncMode value, you can bring data into the MATLAB workspace with one of the synchronous read functions such as fscanf, fgetl, fgets, or fread.

    This property is available only for Serial, TCPIP, UDP, and VISA-serial objects. The possible values are as follows. The default value is enclosed in braces ({}).

    {continuous}

    Continuously query the instrument to determine if data is available to be read.

    manual

    Manually read data from the instrument using the readasync function.

    You can configure RecordDetail to be compact or verbose. If RecordDetail is compact, the number of values written to the instrument, the number of values read from the instrument, the data type of the values, and event information are saved to the record file. If RecordDetail is verbose, the data transferred to and from the instrument is also saved to the record file.

    The verbose record file structure is shown in Recording Information to Disk.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {compact}

    The number of values written to the instrument, the number of values read from the instrument, the data type of the values, and event information are saved to the record file.

    verbose

    The data written to the instrument, and the data read from the instrument are also saved to the record file.

    This property is read-only.

    You can configure RecordMode to be overwrite, append, or index. If RecordMode is overwrite, then the record file is overwritten each time recording is initiated. If RecordMode is append, then data is appended to the record file each time recording is initiated. If RecordMode is index, a different record file is created each time recording is initiated, each with an indexed filename.

    You can configure RecordMode only when the object is not recording. You terminate recording with the record function. A object that is not recording has a RecordStatus property value of off.

    You specify the record filename with the RecordName property. The indexed filename follows a prescribed set of rules. Refer to Specifying a File Name for a description of these rules.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {overwrite}

    The record file is overwritten.

    append

    Data is appended to the record file.

    index

    Multiple record files are written, each with an indexed filename.

    Example

    Suppose you create the serial port object s on a Windows machine associated with the serial port COM1.

    s = serial('COM1');
    fopen(s)

    Specify the record filename with the RecordName property, configure RecordMode to index, and initiate recording.

    s.RecordName = 'myrecord.txt';
    s.RecordMode = 'index';
    record(s)

    The record filename is automatically updated with an indexed filename after recording is turned off.

    record(s,'off')
    s.RecordName
    
    ans =
    myrecord01.txt

    Disconnect s from the instrument, and remove s from memory and from the MATLAB workspace.

    fclose(s)
    delete(s)
    clear s

    This property is read-only.

    Name of the record file. You can specify any value for RecordName — including a directory path — provided the filename is supported by your operating system.

    The MATLAB software supports any filename supported by your operating system. However, if you access the file through the MATLAB workspace, you might need to specify the filename using single quotes. For example, suppose you name the record file my record.txt. To type this file at the MATLAB Command Window, you must include the name in quotes.

    type('my record.txt')

    You can specify whether data and event information are saved to one disk file or to multiple disk files with the RecordMode property. If RecordMode is index, then the filename follows a prescribed set of rules. Refer to Specifying a File Name for a description of these rules.

    You can configure RecordName only when the object is not recording. You terminate recording with the record function. An object that is not recording has a RecordStatus property value of off.

    This property is read-only.

    You can configure RecordStatus to be off or on with the record function. If RecordStatus is off, then data and event information are not saved to a record file. If RecordStatus is on, then data and event information are saved to the record file specified by RecordName.

    Use the record function to initiate or complete recording. RecordStatus is automatically configured to reflect the recording state.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {off}

    Data and event information are not written to a record file

    on

    Data and event information are written to a record file

    This property is read-only.

    Status can be open or closed. If Status is closed, the object is not connected to the instrument. If Status is open, the object is connected to the instrument.

    Before you can write or read data, you must connect the object to the instrument with the fopen function. You use the fclose function to disconnect an object from the instrument.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {closed}

    The object is not connected to the instrument.

    open

    The object is connected to the instrument.

    Value that uniquely identifies an instrument object.

    Tag is particularly useful when constructing programs that would otherwise need to define the instrument object as a global variable, or pass the object as an argument between callback routines.

    You can return the instrument object with the instrfind function by specifying the Tag property value.

    Example

    Suppose you create a serial port object on a Windows machine associated with the serial port COM1.

    s = serial('COM1');
    fopen(s);

    You can assign s a unique label using Tag.

    s.Tag = 'MySerialObj'

    You can access s in the MATLAB workspace or in a file using the instrfind function and the Tag property value.

    s1 = instrfind('Tag','MySerialObj');

    For serial, TCPIP, UDP, and VISA-serial objects, you can configure Terminator to an integer value ranging from 0 to 127, to the equivalent ASCII character, or to empty (''). For example, to configure Terminator to a carriage return, you specify the value to be CR or 13. To configure Terminator to a line feed, you specify the value to be LF or 10. For serial port objects, you can also set Terminator to CR/LF or LF/CR. If Terminator is CR/LF, the terminator is a carriage return followed by a line feed. If Terminator is LF/CR, the terminator is a line feed followed by a carriage return. Note that there are no integer equivalents for these two values.

    Additionally, you can set Terminator to a 1-by-2 cell array. The first element of the cell is the read terminator and the second element of the cell array is the write terminator.

    When performing a write operation using the fprintf function, all occurrences of \n are replaced with the Terminator value. Note that %s\n is the default format for fprintf. A read operation with fgetl, fgets, or fscanf completes when the Terminator value is read. The terminator is ignored for binary operations.

    You can also use the terminator to generate a bytes-available event when the BytesAvailableFcnMode is set to terminator.

    An integer value ranging from 0 to 127, the equivalent ASCII character, or empty (''). For serial port objects, CR/LF and LF/CR are also accepted values. You specify different read and write terminators as a 1-by-2 cell array.

    Example

    This example shows how to set the terminator for a serial port object.

    Create a serial port object associated with the COM1 port. The oscilloscope you are connecting to over the serial port is configured to a baud rate of 9600 and a carriage return terminator, so set the serial port object to those values.

    s = serial('COM1');
    s.Baudrate = 9600;
    s.Terminator = 'CR';

    Maximum time (in seconds) to wait to complete a read or write operation.

    If a timeout occurs, then the read or write operation aborts. Additionally, if a timeout occurs during an asynchronous read or write operation, then:

    • An error event is generated.

    • The callback function specified for ErrorFcn is executed.

    Note

    Timeouts are rounded upwards to full seconds.

    You can configure the Timeout to be the maximum time in seconds to wait to complete a read or write operation for most interfaces.

    Example

    Create a GPIB object g associated with a National Instruments GPIB controller with board index 0, and an instrument with primary address 1.

    g = gpib('ni',0,1);

    You might want to configure the timeout value to a half minute to account for slow data transfer.

    g.Timeout = 30;

    Then when you connect to the instrument and do a data read and write, the timeout value of 30 seconds is used.

    Callback function to execute when a timer event occurs. A timer event occurs when the time specified by the TimerPeriod property passes. Time is measured relative to when the object is connected to the instrument with fopen.

    Note

    A timer event can be generated at any time during the instrument control session.

    If the RecordStatus property value is on, and a timer event occurs, the record file records this information:

    • The event type as Timer

    • The time the event occurred using the format day-month-year hour:minute:second:millisecond

    Some timer events might not be processed if your system is significantly slowed or if the TimerPeriod value is too small.

    Time, in seconds, that must pass before the callback function specified for TimerFcn is called. Time is measured relative to when the object is connected to the instrument with fopen.

    Some timer events might not be processed if your system is significantly slowed or if the TimerPeriod value is too small.

    The default value is 1 second. The minimum value is 0.01 second.

    This property is read-only.

    TransferStatus can be idle, read, write, or read&write. If TransferStatus is idle, then no asynchronous read or write operations are in progress. If TransferStatus is read, then an asynchronous read operation is in progress. If TransferStatus is write, then an asynchronous write operation is in progress. If TransferStatus is read&write, then both an asynchronous read and an asynchronous write operation are in progress.

    You can write data asynchronously using the fprintf or fwrite functions. You can read data asynchronously using the readasync function, or by configuring ReadAsyncMode to continuous (serial, TCPIP, UDP, and VISA-serial objects only). For detailed information about asynchronous read and write operations, refer to Communicating with Your Instrument.

    While readasync is executing for any instrument object, TransferStatus might indicate that data is being read even though data is not filling the input buffer. However, if ReadAsyncMode is continuous, TransferStatus indicates that data is being read only when data is actually filling the input buffer.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {idle}

    No asynchronous operations are in progress.

    read

    An asynchronous read operation is in progress.

    write

    An asynchronous write operation is in progress.

    read&write

    Asynchronous read and write operations are in progress.

    This property is read-only.

    Type of the object. Type is automatically defined after the instrument object is created with the serial, gpib, or visa function.

    Using the instrfind function and the Type value, you can quickly identify instrument objects of a given type.

    gpib

    The object type is GPIB.

    serial

    The object type is serial port.

    tcpip

    The object type is TCPIP.

    udp

    The object type is UDP.

    visa-gpib

    The object type is VISA-GPIB.

    visa-vxi

    The object type is VISA-VXI.

    visa-gpib-vxi

    The object type is VISA-GPIB-VXI.

    visa-serial

    The object type is VISA-serial.

    The value is automatically determined when the instrument object is created.

    Example

    Create a serial port object on a Windows machine associated with the serial port COM1. The value of the Type property is serial, which is the object class.

    s = serial('COM1');
    s.Type
    
    ans =
    serial
    

    Data to store that you want to associate with an instrument object. The object does not use this data directly, but you can access it using dot notation.

    Example

    Create the serial port object on a Windows machine associated with the serial port COM1.

    s = serial('COM1');

    You can associate data with s by storing it in UserData.

    coeff.a = 1.0;
    coeff.b = -1.25;
    s.UserData = coeff

    This property is read-only.

    Total number of values read from the instrument. The value is updated after each successful read operation, and is set to 0 after the fopen function is issued. If the terminator is read from the instrument, then this value is reflected by ValuesReceived.

    If you are reading data asynchronously, use the BytesAvailable property to return the number of bytes currently available in the input buffer.

    When performing a read operation, the received data is represented by values rather than bytes. A value consists of one or more bytes. For example, one uint32 value consists of four bytes.

    Suppose you create a serial port object on a Windows machine associated with the serial port COM1.

    s = serial('COM1');
    fopen(s)

    If you write the RS232? command, and then read back the response using fscanf, ValuesReceived is 17 because the instrument is configured to send the LF terminator.

    fprintf(s,'RS232?')
    out = fscanf(s)
    out =
    9600;0;0;NONE;LF
    
    s.ValuesReceived
    
    ans =
        17

    This property is read-only.

    Total number of values written to the instrument. The value is updated after each successful write operation, and is set to 0 after the fopen function is issued. If you are writing the terminator, then ValuesSent reflects this value.

    If you are writing data asynchronously, use the BytesToOutput property to return the number of bytes currently in the output buffer.

    When performing a write operation, the transmitted data is represented by values rather than bytes. A value consists of one or more bytes. For example, one uint32 value consists of four bytes.

    Example

    Create a serial port object on a Windows machine associated with the serial port COM1.

    s = serial('COM1');
    fopen(s)

    If you write the *IDN? command using the fprintf function, then ValuesSent is 6 because the default data format is %s\n, and the terminator was written.

    fprintf(s,'*IDN?')
    s.ValuesSent
    
    ans =
        6

    Serial Port Properties

    Configure BreakInterruptFcn to execute a callback function when a break-interrupt event occurs. A break-interrupt event is generated by the serial port when the received data is in an off (space) state longer than the transmission time for one byte.

    Note

    A break-interrupt event can be generated at any time during the instrument control session.

    If the RecordStatus property value is on, and a break-interrupt event occurs, the record file records this information:

    • The event type as BreakInterrupt

    • The time the event occurred using the format day-month-year hour:minute:second:millisecond

    Configure PinStatusFcn to execute a callback function when a pin status event occurs. A pin status event occurs when the Carrier Detect (CD), Clear to Send (CTS), Data Set Ready (DSR) or Ring Indicator (RI) pin changes state. A serial port pin changes state when it is asserted or unasserted. Information about the state of these pins is recorded in the PinStatus property.

    Note

    A pin status event can be generated at any time during the instrument control session.

    If the RecordStatus property value is on, and a pin status event occurs, the record file records this information:

    • The event type as PinStatus

    • The pin that changed its state, and pin state as either on or off

    • The time the event occurred using the format day-month-year hour:minute:second:millisecond

    Serial and VISA-Serial Properties

    Bit transmit rate in bits per second. The transferred bits include the start bit, the data bits, the parity bit (if used), and the stop bits. However, only the data bits are stored.

    The baud rate is the rate at which information is transferred in a communication channel. In the serial port context, "9600 baud" means that the serial port is capable of transferring a maximum of 9600 bits per second. If the information unit is one baud (one bit), then the bit rate and the baud rate are identical. If one baud is given as 10 bits, (for example, eight data bits plus two framing bits), the bit rate is still 9600 but the baud rate is 9600/10, or 960. You always configure BaudRate as bits per second. Therefore, in the above example, set BaudRate to 9600.

    Note

    Both the computer and the instrument must be configured to the same baud rate before you can successfully read or write data.

    Your system computes the acceptable rates by taking the baud base, which is determined by your serial port, and dividing it by a positive whole number divisor. The system will try to find the best match by modifying the divisor. For example, if:

    baud base = 115200 bits per second
    divisors = 1,2,3,4,5….
    Possible BaudRates = 115200, 57600, 38400, 28800, 23040…. 
    

    Your system may further limit the available baud rates to conform to specific conventions or standards. In the above example, for instance, 23040 bits/sec may not be available on all systems.

    Example

    This example shows how to set the baud rate for a serial port object.

    Create a serial port object associated with the COM1 port. The oscilloscope you are connecting to over the serial port is configured to a baud rate of 115200 and a carriage return terminator, so set the serial port object to those values.

    s = serial('COM1');
    s.Baudrate = 115200;
    s.Terminator = 'CR';

    You can configure DataBits to be 5, 6, 7, or 8. Data is transmitted as a series of five, six, seven, or eight bits with the least significant bit sent first. At least seven data bits are required to transmit ASCII characters. Eight bits are required to transmit binary data. Five and six bit data formats are used for specialized communication equipment.

    Note

    Both the computer and the instrument must be configured to transmit the same number of data bits.

    In addition to the data bits, the serial data format consists of a start bit, one or two stop bits, and possibly a parity bit. You specify the number of stop bits with the StopBits property, and the type of parity checking with the Parity property.

    You can configure DataTerminalReady to be on or off. If DataTerminalReady is on, the Data Terminal Ready (DTR) pin is asserted. If DataTerminalReady is off, the DTR pin is unasserted.

    In normal usage, the DTR and Data Set Ready (DSR) pins work together, and are used to signal if instruments are connected and powered. However, there is nothing in the RS-232 or the RS-485 standard that states the DTR pin must be used in any specific way. For example, DTR and DSR might be used for handshaking. You should refer to your instrument documentation to determine its specific pin behavior.

    You can return the value of the DSR pin with the PinStatus property. Handshaking is described in Control Pins.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {on}

    The DTR pin is asserted.

    off

    The DTR pin is unasserted.

    You can configure FlowControl to be none, hardware, or software. If FlowControl is none, then data flow control (handshaking) is not used. If FlowControl is hardware, then hardware handshaking is used to control data flow. If FlowControl is software, then software handshaking is used to control data flow.

    Hardware handshaking typically utilizes the Request to Send (RTS) and Clear to Send (CTS) pins to control data flow. Software handshaking uses control characters (Xon and Xoff) to control data flow. To learn more about hardware and software handshaking, refer to Use Serial Port Control Pins.

    You can return the value of the CTS pin with the PinStatus property. You can specify the value of the RTS pin with the RequestToSend property. However, if FlowControl is hardware, and you specify a value for RequestToSend, then that value might not be honored.

    If you set the FlowControl property to hardware on a serial object, and a hardware connection is not detected, the fwrite and the fprintf functions will return an error message. This occurs if a device is not connected, or a connected device is not asserting that is ready to receive data. Check your remote device's status and flow control settings to see if hardware flow control is causing errors in MATLAB.

    Note

    If you want to check to see if the device is asserting that it is ready to receive data, set the FlowControl to none. Once you connect to the device check the PinStatus structure for ClearToSend. If ClearToSend is off, there is a problem on the remote device side. If ClearToSend is on, there is a hardware FlowControl device prepared to receive data and you can execute fprintf and fwrite.

    Although you might be able to configure your instrument for both hardware handshaking and software handshaking at the same time, the toolbox does not support this behavior.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {none}

    No flow control is used.

    hardware

    Hardware flow control is used.

    software

    Software flow control is used.

    You can configure Parity to be none, odd, even, mark, or space. If Parity is none, parity checking is not performed and the parity bit is not transmitted. If Parity is odd, the number of mark bits (1s) in the data is counted, and the parity bit is asserted or unasserted to obtain an odd number of mark bits. If Parity is even, the number of mark bits in the data is counted, and the parity bit is asserted or unasserted to obtain an even number of mark bits. If Parity is mark, the parity bit is asserted. If Parity is space, the parity bit is unasserted.

    Parity checking can detect errors of one bit only. An error in two bits might cause the data to have a seemingly valid parity, when in fact it is incorrect. To learn more about parity checking, refer to Parity Bit.

    In addition to the parity bit, the serial data format consists of a start bit, between five and eight data bits, and one or two stop bits. You specify the number of data bits with the DataBits property, and the number of stop bits with the StopBits property.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {none}

    No parity checking

    odd

    Odd parity checking

    even

    Even parity checking

    mark

    Mark parity checking

    space

    Space parity checking

    Example

    This example shows how to set the parity for a serial port object.

    Create a serial port object associated with the COM1 port. The default setting for Parity is none, so if you want to use parity checking, change the value to the type you want to use, for example, odd.

    s = serial('COM1');
    s.Parity = 'odd';

    This property is read-only.

    PinStatus is a structure array that contains the fields CarrierDetect, ClearToSend, DataSetReady and RingIndicator. These fields indicate the state of the Carrier Detect (CD), Clear to Send (CTS), Data Set Ready (DSR) and Ring Indicator (RI) pins, respectively. Refer to Control Pins to learn more about these pins.

    PinStatus can be on or off for any of these fields. A value of on indicates the associated pin is asserted. A value of off indicates the associated pin is unasserted. For serial port objects, a pin status event occurs when any of these pins changes its state. A pin status event executes the file specified by PinStatusFcn.

    In normal usage, the Data Terminal Ready (DTR) and DSR pins work together, while the Request To Send (RTS) and CTS pins work together. You can specify the state of the DTR pin with the DataTerminalReady property. You can specify the state of the RTS pin with the RequestToSend property.

    Refer to Connect Two Modems for an example that uses PinStatus.

    The possible values are as follows. The default value is instrument dependent.

    off

    The associated pin is asserted

    on

    The associated pin is asserted

    This property is read-only.

    You configure Port to be the name of a serial port on your platform. Port specifies the physical port associated with the object and the instrument.

    When you create a serial port or VISA-serial object, Port is automatically assigned the port name specified for the serial or visa function.

    You can configure Port only when the object is disconnected from the instrument. You disconnect an object with the fclose function. A disconnected object has a Status property value of closed.

    The value is determined when the instrument object is created.

    Example

    Suppose you create a serial port and VISA-serial object associated with serial port COM1.

    s = serial('COM1') 
    vs = visa('ni','ASRL1::INSTR')

    The Port property values are given below.

    [s vs].Port
    ans = 
        'COM1'
        'ASRL1'

    You can configure RequestToSend to be on or off. If RequestToSend is on, the Request to Send (RTS) pin is asserted. If RequestToSend is off, the RTS pin is unasserted.

    In normal usage, the RTS and Clear to Send (CTS) pins work together, and are used as standard handshaking pins for data transfer. In this case, RTS and CTS are automatically managed by the DTE and DCE. However, there is nothing in the RS-232, or the RS-484 standard that states the RTS pin must to be used in any specific way. Therefore, if you manually configure the RequestToSend value, it is probably for nonstandard operations.

    If your instrument does not use hardware handshaking in the standard way, and you need to manually configure RequestToSend, then you should configure the FlowControl property to none. Otherwise, the RequestToSend value that you specify might not be honored. Refer to your instrument documentation to determine its specific pin behavior.

    You can return the value of the CTS pin with the PinStatus property. Handshaking is described in Control Pins.

    The possible values are as follows. The default value is enclosed in braces ({}).

    {on}

    The RTS pin is asserted.

    off

    The RTS pin is unasserted.

    You can configure StopBits to be 1, 1.5, or 2 for serial port objects, or 1 or 2 for VISA-serial objects. If StopBits is 1, one stop bit is used to indicate the end of data transmission. If StopBits is 2, two stop bits are used to indicate the end of data transmission. If StopBits is 1.5, the stop bit is transferred for 150% of the normal time used to transfer one bit.

    Note

    Both the computer and the instrument must be configured to transmit the same number of stop bits.

    In addition to the stop bits, the serial data format consists of a start bit, between five and eight data bits, and possibly a parity bit. You specify the number of data bits with the DataBits property, and the type of parity checking with the Parity property.

    The possible values for Serial Port objects are as follows. The default value is enclosed in braces ({}).

    {1}

    One stop bit is transmitted to indicate the end of a byte.

    1.5

    The stop bit is transferred for 150% of the normal time used to transfer one bit.

    2

    Two stop bits are transmitted to indicate the end of a byte.

    The possible values for VISA-serial objects are as follows. The default value is enclosed in braces ({}).

    {1}

    One stop bit is transmitted to indicate the end of a byte.

    2

    Two stop bits are transmitted to indicate the end of a byte

    Example

    This example shows how to set the StopBits for a serial port object.

    Create a serial port object associated with the COM1 port. The default setting for StopBits is 1 for serial port objects. Change the value to use two stop bits to indicate the end of data transmission.

    s = serial('COM1');
    s.StopBits = 2;

    Examples

    collapse all

    This example creates the serial port object s1 on a Windows machine associated with the serial port COM1.

    s1 = serial('COM1');

    The Type, Name, and Port properties are automatically configured.

    s1.Type
    ans = 
        serial
    s1.Name
    ans = 
        Serial-COM1
    s1.Port
    ans = 
        COM

    To specify properties during object creation,

    s2 = serial('COM2','BaudRate',1200,'DataBits',7);

    Tips

    At any time, you can use the instrhelp function to view a complete listing of properties and functions associated with serial port objects.

    instrhelp serial

    When you create a serial port object, these property values are automatically configured:

    • Type is given by serial.

    • Name is given by concatenating Serial with the port specified in the serial function.

    • Port is given by the port specified in the serial function.

    You can specify the property names and property values using any format supported by the set function. For example, you can use property name/property value cell array pairs. Additionally, you can specify property names without regard to case, and you can make use of property name completion. For example, the following commands are all valid.

    s = serial('COM1','BaudRate',4800);
    s = serial('COM1','baudrate',4800);
    s = serial('COM1','BAUD',4800);

    Before you can communicate with the instrument, it must be connected to obj with the fopen function. A connected serial port object has a Status property value of open. An error is returned if you attempt a read or write operation while obj is not connected to the instrument. You can connect only one serial port object to a given serial port.

    Version History

    Introduced before R2006a

    expand all

    R2022a: Warns

    serial will be removed in a future release. Use serialport instead.

    This example shows how to connect to a serial port using the recommended functionality.

    FunctionalityUse This Instead
    s = serial("COM1");
    s.BaudRate = 115200;
    fopen(s)
    s = serialport("COM1",115200);

    The recommended interface has additional capabilities and improved performance. See Transition Your Code to serialport Interface for more information about using the recommended functionality.