ADVANCED: CALLBACK

Top  Previous  Next

CALLBACK is used in relation to the declaration and usage of callback functions.
 
A callback function is a mechanism where a VPL function is called externally from either the firmware or from an RTCU M2M Platform SDK extension module. The canitpOpen function is an example of the use of a callback function to signal data reception.

Using a program architecture utilizing the callback functionality supports an event-driven design that can prove to take fewer resources, be more responsive, and yield a better code structure.

 
The CALLBACK keyword can be used both as an attribute to a function, but also as a variable type for holding a reference to a callback function.

The address-of operator @ is used to get the address of a callback function.

 

 
Below is a simple example of using the callback functionality:

 

INCLUDE rtcu.inc

 

FUNCTION CALLBACK myTimer;

VAR_INPUT

  no  : INT;

  arg : DINT;

END_VAR;

DebugFmt(message:="Timer#\1,arg=\4",v1:=no,v4:=arg);

END_FUNCTION;

 

 

PROGRAM test;

 

clockStart(no:=0,freq:=2,func:=@myTimer,arg:=2);
clockStart(no:=1,freq:=5,func:=@myTimer,arg:=5);

clockStart(no:=2,freq:=10,func:=@myTimer,arg:=10);

 

WHILE TRUE DO

  Sleep(delay:=1000);

END_WHILE;

 

END_PROGRAM;

 

The above function uses an inbuilt timer functionality to install three timers that each calls the callback at a given frequency. The first timer is called every 2 seconds, the second timer every 5 seconds, and the last timer every 10 seconds.

The output when running the program are as follows:

 

10:42:43 -> Timer#0,arg=2

10:42:45 -> Timer#0,arg=2

10:42:47 -> Timer#0,arg=2

10:42:47 -> Timer#1,arg=5

10:42:49 -> Timer#0,arg=2

10:42:51 -> Timer#0,arg=2

10:42:52 -> Timer#1,arg=5

10:42:52 -> Timer#2,arg=10

10:42:53 -> Timer#0,arg=2

10:42:55 -> Timer#0,arg=2

10:42:57 -> Timer#0,arg=2

10:42:57 -> Timer#1,arg=5

10:42:59 -> Timer#0,arg=2

10:43:01 -> Timer#0,arg=2

10:43:02 -> Timer#1,arg=5

10:43:02 -> Timer#2,arg=10

10:43:03 -> Timer#0,arg=2

10:43:05 -> Timer#0,arg=2

10:43:07 -> Timer#0,arg=2

10:43:07 -> Timer#1,arg=5

10:43:09 -> Timer#0,arg=2

10:43:11 -> Timer#0,arg=2

10:43:12 -> Timer#1,arg=5

10:43:12 -> Timer#2,arg=10

 

 

The clockStart function used is declared as follows:

 

 

FUNCTION ALIGN clockStart : INT;
VAR_INPUT

  no   : INT; //clock number from 0..9

  freq : INT;  //in seconds. Set to 0 to stop clock.

  func : CALLBACK; //callback function with the following parameters: no:int, arg:dint

  arg  : DINT; //argument

END_VAR;

END_FUNCTION;

 

The clockStart function is only supported on NX32L architecture devices.

 

 

For more detailed information on the implementation of callback functions, please refer to the RTCU M2M Platform SDK.