| Contents | Index |
| On this page… |
|---|
Example — Introduction to Events and Callbacks Event Types and Callback Properties Responding To Event Information Creating and Executing Callback Functions |
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, you can 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. |
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
You can see the code for the built-in instrcallback function by using the type command.
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 Type | Associated Properties |
|---|---|
Break interrupt | |
Bytes available | |
Error | |
Output empty | |
Pin status | |
Timer | |
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.
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.
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.
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.
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.
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.
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 Type | Field | Field 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, 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 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 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 error event uses the Message field to store the descriptive message that is generated when an error occurs.
You can specify the callback function to be executed when a specific event type occurs by including 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. |
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.
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.
Create a serial port object — Create the serial port object s associated with serial port COM1.
s = serial('COM1');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;
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)
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
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
![]() | Writing and Reading Data | Using Control Pins | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |