Use Callbacks for Serial Port Communication

Callback Properties

The properties and functions associated with callbacks are as follows.

Property or FunctionPurpose
NumBytesAvailableNumber of bytes available to read
BytesAvailableFcnBytes available callback function
BytesAvailableFcnCountNumber of bytes of data to trigger callback
BytesAvailableFcnModeBytes available callback trigger mode
configureCallbackSet serial port callback function and trigger

Using Callbacks

This example uses a loopback device with the callback function readSerialData to return data to the command line when a terminator is read.


This example is Windows® specific.

  1. Create the callback function — Define a callback function readSerialData that performs a terminated string read and returns the data.

    function readSerialData(src,~)
        data = readline(src);
  2. Create an instrument object — Create the serial port object s associated with serial port COM1.

    s = serialport("COM1",9600);
  3. Configure properties — Configure s to execute the callback function readSerialData when the terminator is read.

  4. Disconnect and clean up — Clear the objects from the MATLAB® workspace when you are done.

    clear s