Use Callbacks for Serial Port Communication
Callback Properties
The properties and functions associated with callbacks are as follows.
| Property or Function | Purpose |
|---|---|
| NumBytesAvailable | Number of bytes available to read |
| BytesAvailableFcn | Bytes available callback function |
| BytesAvailableFcnCount | Number of bytes of data to trigger callback |
| BytesAvailableFcnMode | Bytes available callback trigger mode |
configureCallback | Set 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.
Note
This example is Windows® specific.
Create the callback function — Define a callback function
readSerialDatathat performs a terminated string read and returns the data.function readSerialData(src,~) data = readline(src); disp(data); end
Create an instrument object — Create the serial port object
sassociated with serial port COM1.s = serialport("COM1",9600);Configure properties — Configure
sto execute the callback functionreadSerialDatawhen the terminator is read.configureCallback(s,"terminator",@readSerialData)Disconnect and clean up — Clear the objects from the MATLAB® workspace when you are done.
clear s