Contents

Events and Callbacks

Introduction

You can enhance the power and flexibility of your serial port application by using events. An event occurs after a condition is met and might result in one or more callbacks.

While the serial port object is connected to the device, use events to display a message, display data, analyze data, and so on. Callbacks are controlled through callback properties and callback functions. All event types have an associated callback property. Callback functions are MATLAB® functions that you construct to suit your specific application needs.

You execute a callback when a particular event occurs by specifying the name of the callback function as the value for the associated callback property.

    Note:   All examples in this section on based on a Windows® 32-bit platform. For information about other platforms refer to Overview of a Serial Port Object.

Example — Introduction to Events and Callbacks

This example uses the callback function instrcallback to display a message to the command line when a bytes-available event occurs. The event is generated when the terminator is read.

s = serial('COM1');
fopen(s)
s.BytesAvailableFcnMode = 'terminator';
s.BytesAvailableFcn = @instrcallback;
fprintf(s,'*IDN?')
out = fscanf(s);

MATLAB displays:

BytesAvailable event occurred at 17:01:29 for the object: 
Serial-COM1.

End the serial port session.

fclose(s)
delete(s)
clear s

To see the code for the built-in instrcallback function, use the type command.

Event Types and Callback Properties

The following table describes serial port event types and callback properties. This table has two columns and nine rows. In the first column (event type), the second item (bytes available) applies to rows 2 through 4. Also, in the first column the last item (timer) applies to rows 8 and 9.

Event Types and Callback Properties

Event TypeAssociated Properties

Break interrupt

BreakInterruptFcn

Bytes available

BytesAvailableFcn

BytesAvailableFcnCount

BytesAvailableFcnMode

Error

ErrorFcn

Output empty

OutputEmptyFcn

Pin status

PinStatusFcn

Timer

TimerFcn

TimerPeriod

Break-Interrupt Event

A break-interrupt event is generated immediately after a break interrupt is generated by the serial port. The serial port generates a break interrupt when the received data has been in an inactive state longer than the transmission time for one character.

This event executes the callback function specified for the BreakInterruptFcn property. It can be generated for both synchronous and asynchronous read and write operations.

Bytes-Available Event

A bytes-available event is generated immediately after a predetermined number of bytes are available in the input buffer or a terminator is read, as determined by the BytesAvailableFcnMode property.

If BytesAvailableFcnMode is byte, the bytes-available event executes the callback function specified for the BytesAvailableFcn property every time the number of bytes specified by BytesAvailableFcnCount is stored in the input buffer. If BytesAvailableFcnMode is terminator, the callback function executes every time the character specified by the Terminator property is read.

This event can be generated only during an asynchronous read operation.

Error Event

An error event is generated immediately after an error occurs.

This event executes the callback function specified for the ErrorFcn property. It can be generated only during an asynchronous read or write operation.

An error event is generated when a time-out occurs. A time-out 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.

Output-Empty Event

An output-empty event is generated immediately after the output buffer is empty.

This event executes the callback function specified for the OutputEmptyFcn property. It can be generated only during an asynchronous write operation.

Pin Status Event

A pin status event is generated immediately after the state (pin value) changes for the CD, CTS, DSR, or RI pins. For a description of these pins, see Serial Port Signals and Pin Assignments.

This event executes the callback function specified for the PinStatusFcn property. It can be generated for both synchronous and asynchronous read and write operations.

Timer Event

A timer event is generated when the time specified by the TimerPeriod property passes. Time is measured relative to when the serial port object is connected to the device.

This event executes the callback function specified for the TimerFcn property. Note that some timer events might not be processed if your system is significantly slowed or if the TimerPeriod value is too small.

Responding To Event Information

You can respond to event information in a callback function or in a record file. Event information is stored in a callback function using two fields: Type and Data. The Type field contains the event type, while the Data field contains event-specific information. As described in Creating and Executing Callback Functions, these two fields are associated with a structure that you define in the callback function header. To learn about recording data and event information to a record file, see Debugging: Recording Information to Disk.

The following table shows event types and the values for the Type and Data fields. The table has three columns and 15 rows. Items in the first column (event type) span several rows, as follows:

Break interrupt: rows 1 and 2

Bytes available: rows 3 and 4

Error: rows 5 through 7

Output empty: rows 8 and 9

Pin status: rows 10 through 13

Timer: rows 14 and 15

Event Information

Event TypeFieldField Value

Break interrupt

Type

BreakInterrupt

Data.AbsTime

day-month-year hour:minute:second

Bytes available

Type

BytesAvailable

Data.AbsTime

day-month-year hour:minute:second

Error

Type

Error

Data.AbsTime

day-month-year hour:minute:second

Data.Message

An error string

Output empty

Type

OutputEmpty

Data.AbsTime

day-month-year hour:minute:second

Pin status

Type

PinStatus

Data.AbsTime

day-month-year hour:minute:second

Data.Pin

CarrierDetect, ClearToSend, DataSetReady, or RingIndicator

Data.PinValue

on or off

Timer

Type

Timer

Data.AbsTime

day-month-year hour:minute:second

The following topics describe the Data field values.

The AbsTime Field

The AbsTime field, defined for all events, is the absolute time the event occurred. The absolute time is returned using the clock format: day-month-year hour:minute:second.

The Pin Field

The pin status event uses the Pin field to indicate if the CD, CTS, DSR, or RI pins changed state. For a description of these pins, see Serial Port Signals and Pin Assignments.

The PinValue Field

The pin status event uses the PinValue field to indicate the state of the CD, CTS, DSR, or RI pins. Possible values are on or off.

The Message Field

The error event uses the Message field to store the descriptive message that is generated when an error occurs.

Creating and Executing Callback Functions

To specify the callback function to be executed when a specific event type occurs, include the name of the file as the value for the associated callback property. You can specify the callback function as a function handle or as a string cell array element. Function handles are described in the function_handle reference pages.

For example, to execute the callback function mycallback every time the terminator is read from your device:

s.BytesAvailableFcnMode = 'terminator';
s.BytesAvailableFcn = @mycallback;

Alternatively, you can specify the callback function as a cell array.

s.BytesAvailableFcn = {'mycallback'};

Callback functions require at least two input arguments. The first argument is the serial port object. The second argument is a variable that captures the event information shown in the table, Event Information. This event information pertains only to the event that caused the callback function to execute. The function header for mycallback is:

function mycallback(obj,event)

You pass additional parameters to the callback function by including both the callback function and the parameters as elements of a cell array. For example, to pass the MATLAB variable time to mycallback:

time = datestr(now,0);
s.BytesAvailableFcnMode = 'terminator';
s.BytesAvailableFcn = {@mycallback,time};

Alternatively, you can specify the callback function as a string in the cell array.

s.BytesAvailableFcn = {'mycallback',time};

The corresponding function header is:

function mycallback(obj,event,time)

If you pass additional parameters to the callback function, they must be included in the function header after the two required arguments.

    Note:   You can also specify the callback function as a string. In this case, the callback is evaluated in the MATLAB workspace and no requirements are made on the input arguments of the callback function.

Enabling Callback Functions After They Error

If an error occurs while a callback function is executing the following occurs:

  • The callback function is automatically disabled.

  • A warning is displayed at the command line, indicating that the callback function is disabled.

If you want to enable the same callback function, set the callback property to the same value or disconnect the object with the fclose function. If you want to use a different callback function, the callback is enabled when you configure the callback property to the new value.

Example — Using Events and Callbacks

This example uses the callback function instrcallback to display event-related information to the command line when a bytes-available event or an output-empty event occurs.

  1. Create a serial port object — Create the serial port object s associated with serial port COM1.

    s = serial('COM1');
  2. Configure properties — Configure s to execute the callback function instrcallback when a bytes-available event or an output-empty event occurs. Because instrcallback requires the serial port object and event information to be passed as input arguments, the callback function is specified as a function handle.

    s.BytesAvailableFcnMode = 'terminator';
    s.BytesAvailableFcn = @instrcallback;
    s.OutputEmptyFcn = @instrcallback;
  3. Connect to the device — Connect s to the Tektronix® TDS 210 oscilloscope. Because the default value for the ReadAsyncMode property is continuous, data is asynchronously returned to the input buffer as soon as it is available from the instrument.

    fopen(s)
  4. Write and read data — Write the RS232? command asynchronously to the oscilloscope. This command queries the RS-232 settings and returns the baud rate, the software flow control setting, the hardware flow control setting, the parity type, and the terminator.

    fprintf(s,'RS232?','async')

    instrcallback is called after the RS232? command is sent, and when the terminator is read. The resulting displays are:

    OutputEmpty event occurred at 17:37:21 for the object: 
    Serial-COM1.
    
    BytesAvailable event occurred at 17:37:21 for the object: 
    Serial-COM1.

    Read the data from the input buffer.

    out = fscanf(s)
    out =
    9600;0;0;NONE;LF
  5. Disconnect and clean up — When you no longer need s, disconnect it from the instrument and remove it from memory and from the MATLAB workspace.

    fclose(s)
    delete(s)
    clear s
Was this topic helpful?