Documentation

Use the Default Callback Function

Overview to Callback Example

To illustrate how to use callbacks, this section presents a simple example that creates an OPC Toolbox™ object hierarchy and associates a callback function with the start event, records acquired event, and stop event of the OPC Data Access Group object (dagroup object). For information about all the event callbacks supported by the toolbox, see Event Types.

The example uses the default callback function provided with the toolbox, opccallback. The default callback function displays the name of the object along with information about the type of event that occurred and when it occurred. To learn how to create your own callback functions, see Create and Execute Callback Functions.

Step 1: Create OPC Toolbox Group Objects

This example creates a hierarchy of OPC Toolbox objects for the Matrikon™ Simulation Server. To run this example on your system, you must have the Matrikon Simulation Server installed. Alternatively, you can replace the values used in the creation of the objects with values for a server you can access.

da = opcda('localhost','Matrikon.OPC.Simulation.1');
connect(da);
grp = addgroup(da,'CallbackTest');
itm = additem(grp,{'Random.Real8','Saw-toothed Waves.UInt2'});

Step 2: Configure the Logging Task Properties

For this example, we log 20 records at 0.5-second intervals.

grp.RecordsToAcquire = 20;
grp.UpdateRate = 0.5;

Step 3: Configure the Callback Properties

Set the values of three callback properties. The example uses the default callback function opccallback.

grp.StartFcn = @opccallback;
grp.StopFcn = @opccallback;
grp.RecordsAcquiredFcn = @opccallback;

For this example, specify how often to generate a records acquired event.

grp.RecordsAcquiredFcnCount = 5;

Step 4: Start the Logging Task

Start the dagroup object. The object logs 20 records at 0.5-second intervals, and then stops. With the three callback functions enabled, the object outputs information about each event as it occurs. The records acquired event occurs four times for this example.

start(grp)
OPC Start event occurred at local time 18:52:38
   Group 'CallbackTest': 0 records acquired.
OPC RecordsAcquired event occurred at local time 18:52:41
   Group 'CallbackTest': 5 records acquired.
OPC RecordsAcquired event occurred at local time 18:52:44
   Group 'CallbackTest': 10 records acquired.
OPC RecordsAcquired event occurred at local time 18:52:47
   Group 'CallbackTest': 15 records acquired.
OPC RecordsAcquired event occurred at local time 18:52:49
   Group 'CallbackTest': 20 records acquired.
OPC Stop event occurred at local time 18:52:49
   Group 'CallbackTest': 20 records acquired.

Step 5: Clean Up

Always remove toolbox objects from memory, and the variables that reference them, when you no longer need them.

disconnect(da)
delete(da)
clear da grp itm
Was this topic helpful?