How Can We Help?

Print

Sub Script for Sub Functions in Script Editor

Creating a Sub-script

A sub-script can only be called by a macro instruction — it cannot be run on its own, the way a regular macro instruction can.

The main purpose of sub-scripts is to enable code modularization and improve code reusability. You can break your overall code logic into several sub-scripts, and then call them from within regular macro instructions.

To create a sub-script, follow the steps below:

Add a new sub-script

In the Sub script list, right-click on Sub script and select Add Sub script from the context menu.

Create the Sub Script

Give your sub-script a name (e.g. SubFun0) and write its code in the editor. By default, a new sub-script is generated with a template like:

short subFun0(short nParam)
{
//ToDo
//Edit your code here
return nParam;
}

Edit the sub-script code

short subFun0()
{
//ToDo
int i=3,k=4;
return i+k;
}

 

Call the sub-script from a regular macro

In your regular macro script, include the sub-script’s source file, then call the function directly:

 #include "MacroInit.h"
#include "subFun0.c"
void Macro_main(IN *p)
{
MarcoInit
//ToDo
//int i=3;
LocalWord[0] =subFun0(0);
}

 

Another example, more complex

Create the Sub Script subProcess

short subProcess(short bitEnable, float rawValue, long counter, short threshold)
{
//ToDo
// Declare local variables
float scaledValue;
long newCounter;
short result;
// Check if processing is enabled (bit parameter)
if(bitEnable == 1)
{
// Scale the float value by a fixed coefficient
scaledValue = rawValue * 1.5;
// Increment the long counter
newCounter = counter + 1;
// Compare scaled value against threshold (short)
if(scaledValue > threshold)
{
result = 1;   // Out of range
}
else
{
result = 0;   // Within range
}
}
else
{
// Processing disabled, return default result
result = -1;
scaledValue = 0;
newCounter = counter;
}
// Return short status
return result;
}

 

Call the sub-script from a regular macro

#include "MacroInit.h"
#include "subProcess.c"
void Macro_main(IN *p)
{
MarcoInit
//ToDo
// Declare local variables
short enableBit;
float sensorValue;
long cycleCounter;
short thresholdValue;
short status;
// Read input values
enableBit = LocalBit[40000];          // bit input
sensorValue = LocalWord[40010];      // float input (analog measurement)
cycleCounter = LocalWord[40011];     // long input (counter)
thresholdValue = 100;             // short input (fixed threshold)
// Call the sub function with all parameter types
status = subProcess(enableBit, sensorValue, cycleCounter, thresholdValue);
// Store the result
LocalWord[40000] = status;
// Update alarm bit based on result
if(status == 1)
{
LocalBit[1] = 1;   // Alarm ON
}
else
{
LocalBit[1] = 0;   // Alarm OFF
}
}