TBASIC Custom Functions - An Introduction


1. Overview

TRiLOGI Version 6  supports user-created special functions, known as Custom Functions (the symbol CusFn will be used throughout this manual to mean Custom Functions). Up to 256 CusFns can be programmed using a special language: TBASIC.

TBASIC is derived from the popular BASIC computer language widely used by microcomputer programmers. Some enhancements as well as simplifications have been made to the language to make it more suitable for use in PLC applications.

There are three simple ways to create a new CusFn:

  1. From the "Edit" pull-down menu, select the item "Edit Custom Function" and select the function number from a pop-up CusFn selection table which may range from 1 to 256.  You may also use the hotkey <F7> to open up the selection table. The selection table allows you to define unique and easily identifiable names for each custom function. Once you have selected the custom function the editor window will open up with the contents of that particular custom function.

  2. If you have already created a ladder circuit which connects to either a [CusFn] or [dCusF] function (both appear as menu-items within the "Special Function" pop-up menu), then you can easily open up that particular CusFn by clicking the right mouse button while the highlight bar is at the  [CusFn] or [dCusFn].

2. Custom Function Editor

The custom function editor window allows creation of any number of lines of TBASIC program statements.  Since this is a standard text editor, you should have no problem using the key and mouse controls to edit the text. Pressing <F1> at the text editor window opens up a Help screen which will show you the common keys and mouse actions. E.g. To copy a paragraph of text, select it using the mouse and the press <Ctrl-C>. Move the text editing cursor to the destination and press <Ctrl-V> to paste it to the new location.


3. Custom Function Execution

It is important to understand when and how a TBASIC-based Custom Function is executed with respect to the rest of the program. There are basically two ways in which a CusFn will be executed:

    a.  Triggered by Ladder Logic Special function coil   [CusFn]

A custom function may work the same way as any other special functions in the TRiLOGI ladder diagram programming environment. When you are in ladder circuit editing mode, press <Ins> key to open the "Ins Element" menu.

Select the item or  to create a special function output. A pop-up "Select a Function" menu will appear.

tbasicintro1.gif (13058 bytes)

Select either item:

" D : [CusFn] - Custom created Function"      or
" E : [dCusF] - Diff. Up Custom Functn"

to create a CusFn. You will be required to enter the selected custom function number from 1 to 256. Note that CusFn created using

" E :Diff. Up Custom Functn[dCusF]"

is a "Differentiated Up" instruction. This means that the function will be executed only once every time when its execution condition goes from OFF to ON. Nothing will happen when its execution condition goes from ON to OFF.

On the other hand, using "D: Custom created Function [CusFn]" will mean that the CusFn will be executed every scan as long as its execution condition is ON. This is often not desirable and the coil created using this menu item will be highlighted in RED color to serve as an alarm to programmer. You will probably find that you will use the differentiated version [dCusF] far more frequently.

    b.  Periodic Execution of a Custom Function

There are many situations when you need the PLC to periodically monitor an event or perform an operation. For example, to monitor the temperature reading from a probe or check the real time clock for the scheduled time, and to continuously display changing variables on the LCD display. It is not efficient to use the continuous [CusFn] function for such purposes. It is far better to use the built-in clock pulses to trigger a differentiated Custom function [dCusF]. You can choose a suitable period from 0.01s, 0.02s, 0.05s, 0.1s, 0.2s, 0.5s, 1.0s and 1 minute for the application. Other periods can also be constructed with a self-reset timer. The custom function will only be executed once every period controlled by the system clock pulse or the timer, as follow:

tbasic1.gif (879 bytes)

For example, you don’t need to update the value of a variable displayed on the LCD screen any faster than the human eye can read them. So using a 0.5s clock pulse may be sufficient and this will not take up too much CPU time for the display. For slow processes such as heating, a 1.0s clock pulse to monitor temperature change is more than sufficient.

IMPORTANT

  1. When the CPU scans the ladder logic to a circuit which contains a CusFn, and the execution condition of the circuit is TRUE, the corresponding CusFn will be immediately executed. This means that the CPU will not execute the remaining ladder circuits until it has completed execution of the current CusFn. Hence if the CusFn modifies a certain I/O or variable, it is possible to affect the running of the remaining ladder program.

  2. Note that the INPUT[n] variables contain data obtained at the beginning of the ladder logic scan and not the actual state of the physical input at the time of the CusFn execution. Thus, it will be futile to wait for the INPUT[n] variable to change inside a CusFn unless you execute the REFRESH statement to refresh the physical I/O before you examine the INPUT[n] variable again.

  3. Likewise, any changes to the OUTPUT[n] variable using the SETBIT or CLRBIT statement will not be transferred to the physical outputs until the end of the current ladder logic scan. Hence do not wait for an event to happen immediately after executing a SETBIT or CLRBIT statement on an OUTPUT[n] because nothing will happen to the physical output until the current ladder logic scan is completed.

    If you want to force the output to change immediately you will need to execute the REFRESH statement. Consideration must be given to how such an act may affect the other parts of the ladder program since not the entire ladder program has been executed.

  4. Like all ladder circuits, the relative position of the circuit which triggers the CusFn may affect the way the program works. It is important to consider this fact carefully when writing your ladder program and TBASIC CusFns. Always remember that the CPU executes the ladder logic and CusFn sequentially, even though the equivalent circuits in hard-wired relay may seem to suggest that the different rungs of ladder circuits were to work simultaneously.

  5. In line with the typical Ladder Logic programming rules, a CusFn may appear only once within the ladder diagram, regardless of whether it appears in the normal or differentiated form. A compilation error will occur if a CusFn appears in more than one circuit.

    However, a CusFn may be "CALLed" as a subroutine by any other CusFn and there is no restriction placed on the number of repeated CALL of a CusFn by more than one CusFn. A CusFn may also modify the logic states of an I/O element or the value of internal timers and counters using its powerful TBASIC commands (such as SetBit, ClrBit). The compiler however will not alarm the user that a CusFn may inadvertently alter the logic state of an I/O already controlled by some other ladder circuit.

This power and flexibility offered by the TBASIC-based custom functions must therefore be handled with greater care by the programmer. It is important to prevent conflicting output conditions due to an I/O being controlled or modified at more than one place within a logic scan. The net result is that the logic state of the I/O appears to be in different states at different parts of the ladder circuit. This could lead to bizarre outcomes that may be difficult to trace and debug.

3.2 Interrupt Service CusFn

A CusFn may also serve as an "Interrupt Service Routine" which is executed asynchronously from the normal ladder logic execution. An interrupt-driven CusFn is run when the condition which causes the interrupt occurs. The response time to execution is very short compared to the scan time of the ladder program. There are several interrupt sources which can trigger a CusFn:

  1. Special Interrupt inputs

An M-series PLC contains some special "Interrupt" inputs which, when enabled by the INTRDEF statement, will trigger a particular CusFn defined in the INTRDEF statement when the logic level at the interrupt pin changes state (either from OFF to ON or from ON to OFF).

  1. High Speed Counters (HSC) Reach Target Count

An M-series PLC contains some "High Speed Counter" inputs which, when enabled by the HSCDEF statement, will trigger a particular CusFn defined in the HSCDEF statement when the counter reaches a preset target count value. This enables the CPU to carry out immediate action such as stopping a motor or performing some computation.


4. Simulation & Examination of TBASIC Variables

4.1 Simulation Run of CusFn.

TRiLOGI fully supports simulation of all TBASIC commands. After you have completed coding a CusFn, test the effect of the function by connecting it to an unused input. Run the simulator by pressing <F9> or <Ctrl-F9> key. Execute the CusFn by turning ON its control input. If your CusFn executes a command that affects the logic state of any I/O, the effect can be viewed on the simulator screen immediately. However, if the computation affects only the variables, than you may need to examine the internal variables.

tbasicintro2.gif (15469 bytes)

An I/O or internal relay bit that has been turned ON is indicated by a RED color rectangular lamp that simulate a LED being turned ON. You can pause the logic simulator at any time by pressing the <Ctrl-P> key or clicking on the [Pause] button.  Likewise the simulator engine can be reset by clicking on the [Reset] button.

Simulation of ADC Inputs

Along the top edge of the Programmable Logic Simulator screen, you will find 8 text fields adjacent to  the label "ADC1-8". The programmer can enter the expected ADC values for ADC#1 to #8 in these text fields. In effect, these simulate the potential signal strength at their respective  ADC input pins. These values will be captured by the TBASIC program when  an ADC(n) command is executed in a custom function for ADC #n.

Note: values entered at the ADC input text field will only be updated when the user press the <Enter> key or the <TAB> key to ensure that only finalized entries are used by the TBASIC program. (otherwise, imagine if you try to enter the value 123 at ADC #1, the program would first be receiving  "1", then "12" and then "123" which was not the intention).

4.2 Viewing TBASIC Variables

The values of the internal variables as a result of the simulation run can be viewed by pressing the <V> (which stand for "View") key or by clicking on the [View] button while in the simulation screen. A pop-up window will appear with the values of all the variables as well as special peripheral devices supported by TBASIC. The variables are organized into 4 screens. You can move from screen to screen using the left/right cursor keys or by clicking on the navigation buttons:

tbasicintro2.gif (9614 bytes)

a) Integer  variables Screen

The first screen comprises all 26 32-bit integer variables A-Z, the system DATE and TIME, ADC, DAC, PWM and the resulting values of setLED and setLCD commands. The initial DATE and TIME figures shown during simulation are taken from the PC's internal real-time clock values. However, subsequent values can be affected by the values assigned to the variable DATE[n] and TIME[n].

The present values of the first 3 high speed counters: HSC1 to HSC3 are also shown on this page. Note that ADC data for any particular A/D channel #n will only be shown if an ADC(n) function has been executed. Otherwise the ADC value shown on screen will not reflect the true current value of the ADC port.

b) Data Memory Screen

The second screen displays, in 25 pages, the values of the 16-bit DM variables from DM[1] to DM[4000]. Each page displays 16 rows x 10 columns = 160 DM variables. You can scroll up and down the pages by clicking on the [PgUp] or [PgDn] buttons or using the corresponding keys on the keyboard.

c) String Variable Screen

The third screen displays the value of the 26 string variables A$ to Z$ in 4 pages, depending on the length of each string. If the execution condition is ON and the CusFn is not of the differentiated type, then the CusFn will be continuously executed. The result of the variable will be continuously updated on the viewing window.

d) System Variable Screen

System variables such as INPUT[n] , RELAY[n] and emINT[n] are visible in this screen. You may wish to click on the [Hex] button to view the values in hexadecimal notation as they are more commonly used by programmers to identify the bit patterns in these variables.

4.4 Changing the Contents of Variables

While the "View Special Variables" window is open, you may change the contents of the following variables by clicking on the [Edit] button:

A-Z, A$ to Z$, DM[n], DATE[n], TIME[n], INPUT[n], OUTPUT[n], RELAY[n], TIMERBIT[n], CTRBIT[n], TIMERPV[n], CTRPV[n] and HSCPV[n], emINT[n], emLINT[n].

A text entry window will pop up and you will have to enter the values in the form of assignment statements, such as:

e.g. A = 5000;
DM[99]=5678;
OUTPUT[2]=&H01AB
B$ = "Welcome to TBASIC"

The variable will take up the new value as soon as it is entered, and if the execution condition for any CusFn is ON, the simulator will process the newly entered data immediately and produce the new outcomes. This gives you greater flexibility in controlling the simulation process.

4.6 Decimal and Hexadecimal Representation

All the numeric data shown in the "Special Variables" window are by default displayed in decimal notation. You can display the number in hexadecimal format by clicking on the [Hex] button or by pressing the <H> key. Press the <D> key if you wish to switch back to the decimal format. This feature is very useful for programmers who are familiar with hexadecimal representation of a binary number. The [Hex] button will become the [Dec] button when you enter the Hex display mode.


5. On-line Monitoring of TBASIC Variables

If you execute the "On-Line Monitoring/Control" command from the "Controller" pull-down menu, TRiLOGI Version 5  will continuously query the PLC for the values of all their internal variables. These variables’ values will be updated in real time in the "View Special Variables" window. You may also alter the value of any variables in the PLC using the "Edit Variable" window (by clicking on the "Edit" button at the "View  xxx Variables" window.

This ability of TRiLOGI to provide instant and full visibility of  all the PLC’s internal variables greatly facilitates the programmers’ debugging process. The ease of programming offered by the TRiLOGI programming environment is really what really sets the M-series PLCs far ahead of many other PLCs where both programming and debugging are really painstaking tasks. (This is assuming they have been fully equipped with all the expensive "options" to match the M-series built-in capability!)

5.1    PAUSE and RESET of Target PLC

During On-Line Monitoring, if the "View Special Variables" window is opened, you can still reset the PLC’s internal data by pressing the <Ctrl-R> key. The PLC can also be halted by pressing the <P> key. A halted PLC can subsequently be released from the halted mode by pressing the <P> key again.

5.2    Using LCD Display for Debugging

You should take advantage of the built-in LCD display port of the T100MD to display internal data at the location where you want to track their values, especially if the value changes rapidly which may not be constantly captured by on-line monitoring screen.


6. Error Handling

Since the CusFn text editor does not restrict the type of text that may be entered into its editor, the TRiLOGI compiler will have to check the syntax of the user’s TBASIC program to look out for mis-spelling, missing parameters, invalid commands, etc. Such errors which can be tracked down during compilation process are know as "Syntax Errors".

6.1 Syntax Error

TRiLOGI employs a sophisticated yet extremely user-friendly syntax error tracking system: When a syntax error is encountered, the compilation will be aborted immediately and the CusFn which contains the error is automatically opened in the text editor. The location of the offending word is also highlighted and a pop-up message window reports to you the cause of the error. You can then immediately fix the error and re-compile until all the errors have been corrected.

Error Message

Cause / Action

Undefined symbol found

Only TBASIC commands and legal variable names are allowed. See Chapter 3.

Compiler internal error

Serious trouble, please email to the manufacturer support@tri-plc.com to inform us.

" ) " found without matching " ( "

-

Integer expected

Expect to see either an integer variable or integer constant.

Value is out-of-range

Check the language reference for allowable range of values for the command.

Duplicate line label number

Label for goto must be unique within the same CusFn.

Undefined GOTO destination:

Put a matching label at the place where the GOTO statement is supposed to go.

Invalid GOTO label

@# must be in the range 0-255

Type mismatch (numeric and string types may not mix)

In an expression, strings and integers may not be mixed unless converted using the conversion function. e.g. STR$, VAL, etc.

String is too long

A string is limited to 70 characters

Too many line labels

There should not be more than 20 GOTO labels within the same CusFn.

Unknown Keyword

Most likely wrong spelling for TBASIC statement or function.

WHILE without ENDWHILE

Every WHILE statement must be ended with a matching ENDWHILE statement. Nested WHILE loop must have proper matching ENDWHILE for each WHILE.

IF without ENDIF

Every IF statement must be ended with a matching ENDIF statement to define the boundaries for the block controlled by the IF statement. For multiple IF THEN statement, each IF must be matched by a corresponding ENDIF.

FOR without NEXT

Every FOR statement must be ended with a matching NEXT statement to define the boundaries for the block controlled by the FOR statement. For nested FOR loops, each FOR must be matched by a corresponding NEXT.

Expect keyword "TO"

Required by FOR statement.

Must be an integer

String variable or constant not allowed.

Must be an integer variable only

Integer constant not allowed.

Must be an integer constant only

Integer variable not allowed.

Must be a string

Integer constant or variable not allowed.

Must be a string variable only

String constant not allowed.

Must be a string constant only

String variable not allowed.

Incomplete Expression

Expression not ended properly.

String constant missing closing "

String constants must be enclosed between a pair of opening and closing quotation character (")

Must be Integer A to Z only

index for FOR..NEXT loop must be A-Z.

6.2   Run-Time Errors

Certain errors only become apparent during the execution of the program, e.g. A = B/C . This expression is perfectly OK except when C = 0, then you would have attempted to divide a number by zero, which does not yield any meaningful result. In this case a "run-time error" is said to have occurred. Since run-time errors cannot be identified during compilation, TRiLOGI also checks the validity of a command during simulation run and if a run-time error is encountered, a pop-up message window will report to the programmer the cause and the CusFn where the run-time error took place. This helps the programmer locate the cause of the run-time errors to enable debugging. The possible run-time errors are listed in the following table and they are generally self-explanatory.

Run-Time Error Message

Divide by zero
Call stack overflow! Circular CALL suspected!
FOR-NEXT loop with STEP = 0!
SET_BIT position out-of-range!
CLR_BIT position out-of-range!
TEST_BIT position out-of-range!
STEPSPEED channel out-of-range!
Illegal Pulse Rate for STEPMOVE!
Illegal acceleration for STEPMOVE!
STEPMOVE channel out-of-range!
STEPSTOP channel out-of-range!
ADC channel out-of-range
DAC channel out-of-range
LED Digit # within (1-12) Only!
PWM Channel out-of-range!
LCD Line # must be (1-4) Only!
PM channel out-of-range!
System Variable Index Out-of-range!
Shifting of (A-Z) Out-of-range!
Illegal Opcode - Please Inform Manufacturer!
Timer or Counter # Out-of-Range!