BASIC Ladder Uk 2.20

Download as pdf or txt
Download as pdf or txt
You are on page 1of 129

December 2022

BASIC & Ladder for


TBox -MS, -LITE, -LT2, -Nano

Version: 2.20
BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

The document contains confidential and proprietary information of Ovarro SA and must be kept strictly confidential. It may not be
disclosed in whole or in part under any circumstances without the express prior written consent of Ovarro SA.

General enquiries or enquiries regarding Ovarro SA


permission for use of material contained in Dreve Richelle 161, Waterloo Office Park, E: [email protected]
this document should be addressed to: Building M, Box 35 T: +32(0)2 387 42 59
B-1410 Waterloo
Belgium
Registered Office: Drève Richelle 161, Waterloo Office Park, Building M, Box 35, B-1410 Waterloo, Belgium / La Belgique | Belgium (No.
RLE (Nivelles) 0886.847.541)

Version: 2.20 Page 2 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Revision History
Version Date Description
2.18 19/07/2019 Adding TBox Nano
One note removed section 1.17
Section 1.15: cosmetics in IpToStr and StrToIp
2.19 18/12/2020 New Template
2.20 30/12/2022 Add chapter 1.14.26 : Float functions
Add chapter 1.14.27: Random function
Add in Chapter 1.17: indirect addressing of Text Tag
Version: 2. 20

Author Reviewer 1 Reviewer 2 Reviewer 3 Approver


Jean Burton Jean Burton

Version: 2.20 Page 3 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Contents
PROGRAMS - BASIC ........................................................................................................................................ 9
SEQUENCE OF TASKS .................................................................................................................................................. 9
GENERAL ................................................................................................................................................................ 10
Case .............................................................................................................................................................. 10
Variable not declared ...................................................................................................................................... 10
Statements and 'Line Feed' ............................................................................................................................. 10
Colors ............................................................................................................................................................ 10
Access from the process to the variable ........................................................................................................... 10
Cycle time ...................................................................................................................................................... 11
Distinction between Local – Global – System variables .................................................................................... 11
Break Line ...................................................................................................................................................... 11
Precautions / Miscellaneous ............................................................................................................................ 12
COMMENT .............................................................................................................................................................. 12
CONSTANT.............................................................................................................................................................. 12
ASSIGNMENT........................................................................................................................................................... 13
DIM STATEMENT ...................................................................................................................................................... 14
COMPARISON .......................................................................................................................................................... 15
IF ...THEN ... ELSE … ELSEIF STATEMENT ..................................................................................................................... 16
ARITHMETIC OPERATORS ........................................................................................................................................... 18
General rules of type casting ........................................................................................................................... 18
Special case with constant .............................................................................................................................. 19
Type casting exceptions with MS-CPU16, -LT, -WM, -LP .................................................................................. 19
+ (Addition) ................................................................................................................................................... 20
- (Subtraction) ............................................................................................................................................... 20
* (Multiplication) ........................................................................................................................................... 21
/ (Division) ..................................................................................................................................................... 21
Modulo Operator ............................................................................................................................................ 22
LOGICAL OPERATORS ................................................................................................................................................ 23
Introduction ................................................................................................................................................... 23
AND .............................................................................................................................................................. 23
OR ................................................................................................................................................................. 24
XOR ............................................................................................................................................................... 24
NOT............................................................................................................................................................... 25
FOR...NEXT ...STEP STATEMENT ................................................................................................................................ 26
WHILE...WEND ........................................................................................................................................................ 28
MATHEMATICAL FUNCTIONS ...................................................................................................................................... 29
Trigonometry ................................................................................................................................................. 29
Logarithmic ................................................................................................................................................... 30
Exponential .................................................................................................................................................... 30
Power ............................................................................................................................................................ 31
Square root .................................................................................................................................................... 31

Version: 2.20 Page 4 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

FUNCTIONS (VARIOUS) .............................................................................................................................................. 32


INC ................................................................................................................................................................ 33
DEC ............................................................................................................................................................... 33
ABS ............................................................................................................................................................... 33
LOBYTE ......................................................................................................................................................... 34
HIBYTE .......................................................................................................................................................... 34
LOWORD....................................................................................................................................................... 34
HIWORD ........................................................................................................................................................ 35
SWAPBYTES.................................................................................................................................................. 35
SHL ............................................................................................................................................................... 36
SHR ........................................................................................................................................................... 36
Bit.............................................................................................................................................................. 37
SetBit ........................................................................................................................................................ 37
PackBits ..................................................................................................................................................... 38
SplitBits ..................................................................................................................................................... 39
Split32 ....................................................................................................................................................... 40
Pack32 ....................................................................................................................................................... 40
TriggerPos .................................................................................................................................................. 41
TriggerNeg ................................................................................................................................................. 42
PutChrono .................................................................................................................................................. 42
Truncate .................................................................................................................................................... 43
Odd ........................................................................................................................................................... 43
BCD ........................................................................................................................................................... 43
Sampling tables.......................................................................................................................................... 44
Type Casting .............................................................................................................................................. 45
GetRTUTime, GetRTUDate ......................................................................................................................... 46
Float Functions ........................................................................................................................................... 47
Random Functions ...................................................................................................................................... 48
TEXT FUNCTIONS ..................................................................................................................................................... 49
TIMERS / COUNTERS ................................................................................................................................................. 50
INDIRECT ADDRESSING .......................................................................................................................................... 50
Reading functions .......................................................................................................................................... 50
Writing functions ............................................................................................................................................ 50
Initialization of a Pointer ................................................................................................................................ 51
Note about ‘Address of’ function ..................................................................................................................... 51
GOTO ................................................................................................................................................................... 51
KEYWORDS ............................................................................................................................................................. 52
POU ...................................................................................................................................................................... 53
POU – PROGRAM .................................................................................................................................................... 54
Introduction ................................................................................................................................................... 54
The Program 'Main' ........................................................................................................................................ 54
Creating a Program ........................................................................................................................................ 55
Calling a Program .......................................................................................................................................... 55
POU – FUNCTION .................................................................................................................................................... 56
Introduction ................................................................................................................................................... 56
Creating a Function ........................................................................................................................................ 56

Version: 2.20 Page 5 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Calling a Function from a Program .................................................................................................................. 58


POU – FUNCTION BLOCK .......................................................................................................................................... 59
Introduction ................................................................................................................................................... 59
Creating a Function Block .............................................................................................................................. 59
Calling a Function Block in a POU Program ..................................................................................................... 61
PROGRAMS - LADDER.................................................................................................................................... 63
SEQUENCE OF TASKS OF THE PROCESS ........................................................................................................................ 63
LADDER – PRINCIPLE ................................................................................................................................................ 64
Inputs ............................................................................................................................................................ 64
Outputs ......................................................................................................................................................... 64
Cycle time ...................................................................................................................................................... 65
LADDER - MODES..................................................................................................................................................... 65
Introduction ................................................................................................................................................... 65
Display mode ................................................................................................................................................. 65
Edit mode ...................................................................................................................................................... 66
LADDER - TOOLBAR .................................................................................................................................................. 67
Display mode ................................................................................................................................................. 67
Edit mode ...................................................................................................................................................... 67
VARIABLES .............................................................................................................................................................. 68
Local Tags ..................................................................................................................................................... 68
Global Tags .................................................................................................................................................... 68
The Colors of the Tags .................................................................................................................................... 69
CREATE LADDER DIAGRAM ........................................................................................................................................ 69
Inserting items ............................................................................................................................................... 70
The colors of the Tags ..................................................................................................................................... 70
The Keys ........................................................................................................................................................ 70
STEP BY STEP CREATING OF LADDER ............................................................................................................................ 71
DRAWING LINES IN LADDER …. ................................................................................................................................... 75
FUNCTIONS ............................................................................................................................................................. 76
Analog Comparison Functions......................................................................................................................... 77
Special Functions ........................................................................................................................................... 77
Timer & Counter Functions ............................................................................................................................. 78
Math. Assignments functions ......................................................................................................................... 78
Math. Arithmetic functions ............................................................................................................................. 79
Math. Bitwise functions .................................................................................................................................. 79
Math. Shift functions ...................................................................................................................................... 80
MATHEMATICAL BLOCK ............................................................................................................................................ 81
Introduction ................................................................................................................................................... 81
Type Casting .................................................................................................................................................. 82
Assignments .................................................................................................................................................. 82
Arithmetic operations ..................................................................................................................................... 82
Comparisons .................................................................................................................................................. 83
Bit manipulations ........................................................................................................................................... 83
Boolean operations ........................................................................................................................................ 84
Conversion + Indirect addressing ..................................................................................................................... 84

Version: 2.20 Page 6 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Miscellaneous ................................................................................................................................................ 85
Note about ‘Adr=Tag(Tag)’ function ............................................................................................................ 86
POU (PROGRAM ORGANIZATION UNITS) ..................................................................................................................... 87
POU – PROGRAM .................................................................................................................................................... 88
Introduction ................................................................................................................................................... 88
The Program 'Main' ........................................................................................................................................ 88
Creating a POU Program ................................................................................................................................ 88
Calling a POU Program in another Program .................................................................................................... 90
POU – FUNCTION .................................................................................................................................................... 91
Introduction ................................................................................................................................................... 91
Creating a POU Function ................................................................................................................................ 92
Example of a Function .................................................................................................................................... 94
Calling a POU Function in a POU Program ...................................................................................................... 95
POU - FUNCTION BLOCK ........................................................................................................................................... 96
Introduction ................................................................................................................................................... 96
Creating a POU Function Block ....................................................................................................................... 96
Example of a Function Block ........................................................................................................................... 98
Calling a POU Function Block in a POU Program ............................................................................................. 99
Debugging of a Function block ...................................................................................................................... 100
Indirect addressing inside a Function Block .................................................................................................... 100
TIMERS ........................................................................................................................................................ 101
PRESENTATION ...................................................................................................................................................... 101
INTRODUCTION ...................................................................................................................................................... 102
CREATING A TIMER ................................................................................................................................................. 102
THE VARIABLES OF A TIMER...................................................................................................................................... 103
Saving Dynamic Preset ................................................................................................................................. 104
USING TIMERS IN LADDER........................................................................................................................................ 104
The instance name ....................................................................................................................................... 105
The Preset .................................................................................................................................................... 105
USING TIMERS IN BASIC ......................................................................................................................................... 106
Reminder ..................................................................................................................................................... 106
Syntax ......................................................................................................................................................... 106
Reset Timer Function .................................................................................................................................... 107
Examples ..................................................................................................................................................... 107
USING TIMERS IN POUS .......................................................................................................................................... 107
TIMER – SINGLE SHOT............................................................................................................................................. 108
TIMER – MONOSTABLE ........................................................................................................................................... 109
TIMER – INTEGRAL.................................................................................................................................................. 110
TIMER – ON DELAY ................................................................................................................................................ 112
COUNTERS .................................................................................................................................................. 113
PRESENTATION ...................................................................................................................................................... 113
INTRODUCTION ...................................................................................................................................................... 114
Creating a Counter ....................................................................................................................................... 114

Version: 2.20 Page 7 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

THE VARIABLES OF A COUNTER ................................................................................................................................. 115


USING COUNTERS IN LADDER ................................................................................................................................... 116
The contact used with the pulse input ........................................................................................................... 116
The instance name ....................................................................................................................................... 116
The Preset .....................................................................................................................................................117
USING COUNTERS IN BASIC .................................................................................................................................... 118
Reminder ..................................................................................................................................................... 118
Syntax ......................................................................................................................................................... 118
Reset Counter Function ................................................................................................................................ 118
Using Counters in POUs ................................................................................................................................ 118
COUNTER - UP ...................................................................................................................................................... 119
COUNTER - DOWN ................................................................................................................................................ 121
COUNTER - RING ................................................................................................................................................... 123
LIBRARY MANAGER ..................................................................................................................................... 125
IMPORT OF POUS (SAVING POUS IN A LIBRARY) ......................................................................................................... 125
EXPORT OF POUS (RETRIEVAL OF POUS FROM A LIBRARY) ........................................................................................... 126
USE OF A LIBRARY IN A TWINSOFT DOCUMENT ........................................................................................................... 126
INDEX ................................................................................................................................................................. 127

Version: 2.20 Page 8 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Programs - BASIC
TBOX MS, TBOX LITE, TBOX LT2 and TBOX NANO support 2 languages: BASIC and Ladder.

Both languages are used to execute process automation.


• BASIC is a text language, very easy to use for making calculation.
It supports all advanced mathematical functions.
• LADDER is a graphical language, which should be preferred when Boolean operations are required.
LADDDER is much more efficient than BASIC for handling ‘digital’ Tags.

BASIC and LADDER can be used together


We suggest that you divide your process into several programs ( sub-programs) depending on the process concerned.
According to the kind of process, you create programs in BASIC and programs in LADDER.
Then you combine programs as you want: BASIC calling LADDER and reciprocal.

This section explains the syntax of BASIC.


To see an example, load the TWinSoft document 'MSBASIC.tws' that you find in the 'Samples' directory of TWinSoft.

Example:
' This is my first program
If (Temperature > 70) Or (Emergency=1) then
Pump=1
Alarm=1
endif

Sequence of Tasks
The variables are handled like following:
• Inputs are read before starting the cycle. A copy is used all along the cycle.
• Outputs are written at the end of the cycle. A copy is used all along the cycle.
• Variables are handled immediately in the cycle.

MS-CPU16, -LT, -WM, -LP process cycle MS-CPU32, LT2 process cycle
Sequence of one cycle: Sequence of one cycle:
Reading DI (Reading AI if fast sampling selected) Reading DI and AI
Updating Timer and Counter Variables
1st cycle of Ladder/BASIC Updating ‘Time’ Variables
Handling registers and timer/counter values
“on the fly” 1st cycle of Ladder/BASIC

Writing DO (Writing AO if fast sampling Writing DO and AO


selected)
If new second: handling of
If new second: handling of sampling table
sampling table
Next cycle … Next cycle …

Version: 2.20 Page 9 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

General

Case
BASIC is not case sensitive.

Variable not declared


A variable used within the program and which has not been declared in the list of Tags of the TWinSoft document is refused
during compilation.

A variable must be declared either in the list of Tags (=global Tag), in the list of POU Tags or with a Dim statement (=local
Tag)

Statements and 'Line Feed'


The statements can be separated by a 'Line Feed' or by a colon ‘:’

Example with several assignments:


a=50
b=c
Or
a=50 : b=c

The statements must be on the same line.

Example with if .. then:

if a=50 then
b=c
endif

Colors

Comment : the comments appear in green color

Constant : a constant appears in red color

Keyword : a keyword appears in blue color (see the list at section 1.19)

Variable : a variable appear in black color

Access from the process to the variable


Inputs: the physical inputs are read once at the beginning of the cycle. It means that an input used at several places
in the program, will always be at the same value.

Outputs: the physical outputs are executed at the end of the cycle, according to their last status.

Internal variables: the internal variables (DIV and AIV) are read/executed at the moment they are treated within the
program. It means the changing on a variable is updated everywhere it is used.

Version: 2.20 Page 10 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Cycle time
One cycle corresponds to a complete process (BASIC and LADDER), from the first until the last line.

The cycle time is the time needed to execute one cycle. The cycles are executed permanently, one after each other.

For safety reason, one cycle should never be longer than 1 second. If this occurs, an internal watchdog timer resets the
TBOX automatically (the watchdog is minimum 1.6 second).

The cycle time is available from the ‘RTU Identification’, accessible in the main menu → 'Communication'.

Distinction between Local – Global – System variables


A suffix can be used to make the distinction between the different types of variable.

@ : it is a Global Tag (example: input0@)

# : it is a Local Tag (example: second#)

! : it is a System variable (example: second!)

1. To use System variables without declaring them as Tag, the suffix is mandatory.
2. If there is no suffix, the order of resolution is local Tag if it exists, then global Tag if it
exists. Otherwise the compiler returns an error.
3. The suffix cannot be declared within a DIM statement (it is clear that the variable will be
local).

Examples:
dim Temperature as integer
if Temperature@ > 20 then

if triggerpos(prgrun!) then
......

Temperature@ is the global Tag, if it exists, otherwise the compiler returns an error. It will not use the local
Tag.

Break Line
When a line is very long, it can be cut using the character ‘_’ (underscore).

Examples:
If A=0 Or B=0 Or C=0 Or D=0 Or E=0 Or F=0 Or G=0 Or H=0 Or_
I=0 Or J=0 Or K=0 Or L=0 Or M=0 Or N=0 Or O=0 Or_
P=0 Or Q=0 Or R=0 Or S=0 Or T=0 then
output=0
endif

Version: 2.20 Page 11 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Precautions / Miscellaneous
• When declaring local Tags or arguments to Function or Function block, do not use the same name as global Tags.
• When a Tag is dimensioned within the programming (example: dim Tag as Bool), it is automatically considered
as a local Tag.
• When several operators are used following each other, one needs to separate them with brackets.
Example: if ((a=10) Or (a=20)) And (b=0)) then
• With Timer/Counter functions, if you wish to associate a Tag to ‘Value’ and/or ‘Preset, they must be of type DWORD
(32 bits).

Comment
• Rules
A comment can start with the keyword REM or with the single apostrophe '

REM : is considered as a statement. It can then only be used at the beginning of a line.
' : is not a statement. It can then be placed anywhere in the line.

• Examples
REM this is a comment
' this is a comment
var1=var2 ' var2 is assigned to var1

Constant
• Rules
Constant statement can be expressed in:
➢ Decimal
➢ hexadecimal (with prefix &H)
➢ floating point

• Limits
To be accepted, the constant must hold into a INT 32 bits or into a IEEE 32 bits Floating.

When a constant is used in Timer, the 'time span' is limited to 49 days (=4294967296 ms).

• Examples
decimal: a=123456
hexadecimal: a=&H1E240
Floating point: a=123.456

In an arithmetic operation, a constant is always converted into the format of the


Tag it is associated to.
Integer/2.5
→ Constant will be converted to Integer, it means 2
See also section 1.9.1

Version: 2.20 Page 12 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Assignment
• Syntax
VarName=expr ' variable

Table[x]=expr ' indexed variable, part of a table (array)

[x] is the index of the variable in the table. Only square brackets [ ] can be used.

The keyword LET can be used but is optional: LET a=b

• Indexing
With a local variable 'simple', indexing is not allowed.

With a local variable 'array', index must be specified with the Dim statement.

With a global variable, indexing is allowed. The variable is then considered as the first of a virtual table composed of
successive ModBus addresses. See For...next statement. with Global Tags.

• Examples
Temperature=Setpoint
Delay=5
LET StartPump[2]=1

Version: 2.20 Page 13 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Dim Statement
The Dim statement is used to create Local Tags inside a program. Local Tags can also be created from the list of 'POU Tags'.

• Syntax
Variable

Dim MyVar
Dim MyVar as <Type> ' See types below

Table (array)

Dim Table[n] <as Type> ' Table is an array of n elements (1 to n)


' The types of the elements can also be declared

[n]: must be a constant

Each variable of the table can be represented with the name of the table and its index:

Table[1]

Table[2]

....

The type is optional. If it is not declared, the default format is WORD

• Types available

Types Description
BOOL 1 bit - Digital
BYTE 8 bits - Unsigned
INTEGER 16 bits - Signed
WORD 16 bits - Unsigned
LONG 32 bits - Signed
DWORD 32 bits - Unsigned
SINGLE 32 bits - Float IEEE
TEXT(x) TEXT with x the number of characters

• Examples
Dim Temperature as Single
Dim input2 as Bool
Dim table[4] as Word
Dim Name as Text(20)

Version: 2.20 Page 14 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Comparison
The available comparison operators are:

= : equal to
< : smaller than
<= : smaller than equal to
> : larger than
>= : larger than or equal to
<> : different

The comparison returns a Boolean result. It can be used to compare 2 numbers and get the result in a Bool, or in a sequence
as condition; for instance if ..then.

• Syntax
if (expression1 operator expression2) then

result=(expression1 operator expression2)

• Arguments
result :Bool
expression :any expression composed of Bool, Byte, Word, Long, Float

You can mix several types of variables in the 'expressions'.


• Examples
Status=Value<>0
if (level<=125) then
Pump=1
endif

Version: 2.20 Page 15 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

If ...Then ... Else … Elseif statement


Executes a group of statements according to a condition.

• Syntax
• Classical syntax: with Statements on different lines:

If Condition1 then
Statement1
Statement2
elseif Condition2 then
Statement3
else
Statement4
Endif

In above example:
If Condition1 is TRUE, Statement 1 and 2 are executed.
If Condition1 is FALSE, Condition2 is tested.
If Condition2 is TRUE, Statement3 is executed otherwise Statement4 is executed

The same instructions can be written as follows:

If Condition1 then
Statement1
Statement2
else
if Condition2 then
Statement3
else
Statement4
endif
endif

• Several Statements on the same line: the Statements must be separated by colons:

If Condition then
Statement1 : Statement2
endif

• Condition and Statement in 1 line: Then endif cannot be indicated.

If Condition then Statement1

• Several If ... then statements chained

It is possible to chain several If ... then statements.


In such case, each of them must end with endif keyword.

If Condition1 then
Statement1
If Condition2 then
Statement2
endif
endif

Version: 2.20 Page 16 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

• Arguments
➢ Condition

The condition is Boolean. It can be any expression resulting in TRUE or FALSE status.

Examples:

If Button then ‘(is equivalent to: if Button=1 then)

If Not Button then ‘(is equivalent to: if Button=0 then)

If ((Var1>=15) And (Var1<=25)) then

• Examples
Call of a POU

If (level>100) then
Call StopPump 'StopPump is a POU Program
endif

Start of a Loop on condition

If (Level<15) then
for i=1 to 4
If Pump[i]=0 then
Pump[i]=1
endif
next
endif

Test a value at '0'

If Level then 'The condition is TRUE as long as Level<>0


pump=1
endif

Version: 2.20 Page 17 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Arithmetic operators

General rules of type casting


Type Casting means that several formats of Tags (WORD, FLOAT, …) can be associated in arithmetic operations.

TWinSoft handles type casting automatically, according to “C” rules. TBOX MS32, TBOX-LT2 and TBOX-NANO respect
literally those rules. TBOX MS16 and TBOX LITE have some exceptions described section section1.9.3.

“C” rules in type casting:

Following table gives cast's results of any arithmetic function (+, *, …):

Bool Byte Int Word Long DWord Float


Bool Bool Byte Int Word Long DWord Float
Byte Byte Byte Int Word Long DWord Float
Int Int Int Int Word Long DWord Float
Word Word Word Word Word Long DWord Float
Long Long Long Long Long Long DWord Float
DWord DWord DWord DWord DWord DWord DWord Float
Float Float Float Float Float Float Float Float

The table associates all formats of variables, with in the


middle the format used to calculate the result (of any
operation).

Example:

INT * LONG → calculated in LONG

Conclusions about the above table:


Check there is not risk of overflow or unexpected values because of different formats of Tag. Think of formats of Tag you
combine

Next table determines when variables are automatically casted at compilation:


The general rule is that when
Bool Byte Int Word Long DWord Float
combining several formats,
Bool -       the ‘lowest’ format is
Byte  -      automatically casted to the
Int   - -    ‘highest’.
Word   - -   
Long     - -  Example : Bool + Int
DWord     - - 
Bool will be automatically
Float       - casted to Int

 means automatic casting at compilation

Version: 2.20 Page 18 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Special case with constant


With two constants associated, the same rule is applied as illustrated in the above table.

With constant and Tag, the constant is casted to the format of the Tag it is associated to.

Examples:

RESULT=WORD * 10.9 if WORD=100, RESULT=1100 (you can force the casting of the constant. See
section1.14.24)

RESULT=FLOAT * 10.9 if FLOAT=100, RESULT=1090

RESULT=WORD * 70000 if WORD=100, RESULT=7000000

The constant 70000 cannot be casted into WORD, then the WORD is
casted in DWORD

WORD=MINUTE*100 +SECOND MINUTE is by default in byte format, then MINUTE*100 is computed in BYTE
format. If its result is > 255, the final result will be wrong.
Then you should force the casting of MINUTE (see 1.14.24)

Type casting exceptions with MS-CPU16, -LT, -WM, -LP


When some different formats are associated, the intermediate calculation is done using the “best” format according to the
format of the Result Tag. As this rule could not be applied to ALL combinations, we do not use it anymore with TBOX
MS32, TBOX-LT2 and TBOX-NANO (see section 1.9.1 above)

Examples:

FLOAT = FLOAT + WORD WORD transformed in a FLOAT

LONG = LONG + FLOAT FLOAT rounded to LONG

FLOAT = FLOAT + LONG LONG transformed to FLOAT

WORD = FLOAT + FLOAT Result in WORD with the addition of the FLOAT rounded
LONG = WORD + WORD In case the result of the operation is > 65535, TWinSoft presumes the
result will go to a Long.
Be sure the Tag receiving the result is of format Long
LONG = WORD * WORD same as above

It is also possible to force the casting you want.


See Type Casting functions at section 1.14.24

Version: 2.20 Page 19 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

+ (Addition)
Sums several numbers

• Syntax
result=expression1+expression2+ expression3 ...

• Arguments
result :Byte, Word, Long, Float
expression :any expression composed of Bool, Byte, Word, Long, Float

When mixing several format of variables during arithmetic operations, mind the
type casting ! See section1.9.1 above.

• Examples
Word1=Word2+Float2+Float3 'Result in 'Word' format with Float rounded
Float1=Word2+(Float2*2) 'Result in Float

- (Subtraction)
Gives the difference between numbers or used to change a number to negative.

• Syntax
result=expression1-expression2-expression3 ...
result=-number

• Arguments
result :Byte, Word, Long, Float
expression :any expression composed of Bool, Byte, Word, Long, Float

• Examples
Word1=Word2-Float2-Float3 'Result in 'Word' format with Float rounded
Float1=Word2-(Float2*2) 'Result in Float

With Addition and Subtraction, according to the types used, (Byte, Word or Int) be
attentive to roll over

Version: 2.20 Page 20 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

* (Multiplication)
Multiplies numbers.

• Syntax
result=expression1*expression2*expression3 ...

• Arguments
result :Byte, Word, Long, Float
expression :any expression composed of Bool, Byte, Word, Long, Float.

When mixing several format of variables during arithmetic operations, mind the
type casting ! See section 1.9.1

• Examples
Word1=Word2*Float2*Float3 'Result in 'Word' format with Float rounded
Float1=Word2*Float2*2 'Result in Float

/ (Division)
Divides numbers.

• Syntax
result=expression1/expression2/expression3 ...

• Arguments
result :Byte, Word, Long, Float
expression :any expression composed of Bool, Byte, Word, Long, Float

When a divisor=0 (zero) the result is unpredictable and depends on the type of
'result' variable.
To avoid any problem, you have to check the divisor(s) before executing the
division(s)

• Examples
if (Float2>0) and (Float3>0) then
Word1=Word2/Float2/Float3 'Result in Word with Float rounded
endif

if (Float2>0) then
Float1=Word2/Float2/2 'Result in Float
endif

Version: 2.20 Page 21 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Modulo Operator
Divides 2 numbers and returns the remainder

• Syntax
result=number1 % number2

• Arguments
result :Word, Long, Float
numbers :Word, Long

When mixing several format of variables during arithmetic operations, mind the
type casting ! See section 1.9.1 above.

Both numbers must be positive.


If one number = 0 then result = 0

• Examples
Remainder=47 % 15 'Remainder=2

Version: 2.20 Page 22 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Logical operators

Introduction
There are 2 ways to interpret those operators:
- as Boolean operators
- as Bitwise operators

Boolean operators
This is probably the more usual way to use the logical operators: in an expression you execute Boolean operations between
several Tags.

Example:
if ((Var1>=150) And (Var2<=200)) Or ((Emergency=1) And (Not Button))

Bitwise operators
Those operators are used between 2 Tags and execute Bitwise operations on each bit of the Tags:

AND Operator
OR Operator
XOR Operator
NOT Operator

When using several operators, be careful to the priority of the operations.


We advise to use brackets to separate clearly the operations.
Example: A=2 And B <>3
Without brackets, will be calculated as follows:
(A=((2 And B)<>3))
With brackets, like it is probably required:
(A=2) And (B<>3)

AND
Performs a Bitwise AND operation on 2 expressions.

00110101
11010110
00010100

• Syntax
result=expression1 And expression2

• Arguments
result :Word or Long
expression :any expression composed of Bool, Byte, Word, Long

You can mix several types of variables in the 'expressions': it is automatically converted to the type of the variable 'result'

• Examples
MyVal=Word1 And 255 'Mask to erase the MSB
MyVal=(Word1*2) And Word2

Version: 2.20 Page 23 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

OR
Performs a Bitwise OR operation on 2 expressions.

00110101
11010110
11110111

• Syntax
result=expression1 Or expression2

• Arguments
result :Word or Long
expression :any expression composed of Bool, Byte, Word, Long

You can mix several types of variables in the 'expressions': it is automatically converted to the type of the variable
'result'

• Examples
MyVal=Word1 Or Word2
MyVal=(Word1*2) Or Word2

XOR
Performs a Bitwise XOR operation on 2 expressions.

00110101
11010110
11100011

• Syntax
result=expression1 XOR expression2

• Arguments
result :Word or Long
expression :any expression composed of Bool, Byte, Word, Long

You can mix several types of variables in the 'expressions': it is automatically converted to the type of the variable
'result'

• Examples
MyVal=Word1 XOR Word2
MyVal=(Word1 XOR Word2) And Word2

Version: 2.20 Page 24 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

NOT
Performs a Bitwise NOT operation on 1 expression. It inverts the bits.

11010110
00101001

Notes:
1. The NOT function is a complement to 1
2. An inversion (a=-b) is a (complement to 1) + 1

Examples:

Value NOT Inversion


-2 1 2
-1 0 1
0 -1 0
1 -2 -1
2 -3 -2

• Syntax
result=Not expression

• Arguments
result :Word or Long
expression :any expression composed of Bool, Byte, Word, Long

• Examples
MyVal=Not Word1

Version: 2.20 Page 25 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

For...Next ...Step statement


For...Next is used to repeat several statements, a specified number of times using loops and indexing of table (array).
We speak also of 'index addressing', as we access variables using an index
It is the ideal tool to execute repetitive procedure.
.
• Syntax
➢ For ... next i

Statements are executed n times:

Dim i as Word
For i=x to n step y
Statement
Statement
next i

x : start index. Any number ( >= 1)


n : last index. Any number > x
step y : optional. Increment in the index at each next operation.
If not declared, step = 1.
Must be different than 0

Be careful using big value for i.


With function For…Next, the program jumps out of the routine when all steps have
been executed.
If there are too many, the program might generate a watchdog.
You should then use For … nextcycle

➢ For ... nextcycle

The Statement is executed once at each cycle of the program: This can be useful to balance the resources of a
program, and mandatory when there are a lot of steps.

Dim i as Word
For i=1 to n
Statement
nextcycle i

Index can be an expression.


Example: (i*2)+3

• With local Tags


To use index addressing with local Tags, you must declare a table (array) with its dimension and type.
It cannot be declared from the list of POU Tags, but using code in the program.

Example:
Dim InitValue[3] as Word
Dim i as Word
For i=1 to 3
InitValue[i]=0
next i

In this example, [3] is the size of the array. Only square brackets [ ] can be used

Version: 2.20 Page 26 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

• With global Tags


As global Tags have been created, they already have a type.

The table is composed of one selected Tag, and the following Tags in order of their ModBus addresses from the list of
Tags.

Example: you have 'start' variables you want to activate at the same time.
You create the 4 Tags, with successive ModBus addresses.

Signal Tag ModBus address


IN 0 Start1 256
IN 1 Start2 257
IN 2 Start3 258
IN 3 Start4 259

Dim i as Word
For i=1 to 4
Start1[i]=1
next i

Start1[2] then corresponds to Start2


etc...

• Example
For...Next statements nested

REM start of Pumps and associated lamp.


Dim i as Word
Dim j as Word
If start=1 then
For i=1 to 5
Pump1[i]=1
next i

For j=i+5 to 15 'at this step, i=5 => j=10


Lamp1[i]=1
next j
endif

Version: 2.20 Page 27 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

While...Wend
While...Wend statement executes a loop as long as the condition is TRUE.

Therefore, the rest of the program is not executed as long as the condition is TRUE.

Make sure the loop does not exceed 1 second.


A watchdog is generated after about 1.6 second.
When it is possible, we advise to use the For…Next or For…Nextcycle statements

• Syntax
➢ Classical syntax

While condition
statement1
statement2
Wend

➢ Several While...Wend can be chained

While condition1
statement1
While condition2
statement2
Wend
Wend

• Argument
condition : Bool, Tag or expression

• Example
While level>150
call Alarms
Wend

Version: 2.20 Page 28 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Mathematical Functions

Trigonometry
The trigonometric functions supported are:

Sine, Arcsine, Cosine, Arccosine, Tangent, Arctangent.

All trigonometric functions work with angles expressed in radians.


A circle of 360 degree corresponds to 2  radians

• Syntax
Result=Sin(x)
Result=Cos(x)
Result=Tan(x)
Result=ArcSin(x)
Result=ArcCos(x)
Result=ArcTan(x)

• Argument
x : Single or constant
result : Single

• Examples
‘Calculation of pi
Dim a as Single
Dim Pi as Single
a=arcsin(1)
Pi=a*2

‘Implementation of a sinusoid

if triggerpos (PrgRun!) then Radian=0


if Radian < (Pi*2) then 'Pi*2 = 360 degrees
Radian=Radian + (Pi/180) 'Pi/180 = 1 degree
else
Radian=0
endif

Sine=sin(Radian)
Sinusoid=(sine*90) + 200
Degree=(Radian*180)/pi

Version: 2.20 Page 29 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Logarithmic
The logarithmic functions supported are common logarithms and natural logarithms

➢ Common logarithms have the base 10


Log (10) = 1
Log (100) = 2
Log (1000) = 3

➢ Natural logarithms have the base e.

The constant e is approximately 2.718282.

• Syntax
Result=Log(x)
Result=Ln(x)

• Argument
x : Single or constant
result : Single

Exponential
Exponential function returns e (the base of natural logarithm) raised to a power
The constant e is approximately 2.718282
The Exp function is the complement to natural logarithm function (see above)

• Syntax
Result=Exp(x)

• Argument
x : Single or constant
result : Single

Version: 2.20 Page 30 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Power
The Power function returns the value of a base expression taken to a specified power.

• Syntax
Result=Pow(base, exponent)

• Argument
base : Single or constant
exponent : Single or constant
result : Single

• Example
Power=Pow(10, 3) ‘returns 1000 (10^3)
Power=Pow(0, 0) ‘returns 1
Power=Pow(1, 0) ‘returns 1

When working with Tag(s) as argument, be careful that the result is a Float (IEEE),
with a precision of 7 digits.
Therefore, 10^7 or higher may not return the expected value.

Square root
Returns the square root of a number.

• Syntax
Result=Sqrt(x)

• Argument
x : Single or constant
result : Single

• Example
MySquar=Sqrt(4) ‘returns 2
MySquar=Sqrt(9) ‘returns 3
MySquar=Sqrt(23) ‘returns 4.796
MySquar=Sqrt(0) ‘returns 0

Version: 2.20 Page 31 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Functions (various)
The following Functions are supported. See details in the following pages.

Type Function Description


Operators INC Increment
DEC Decrement
Absolute value ABS
Byte manipulation LOBYTE returns LSB of a WORD
HIBYTE returns MSB of a WORD
LOWORD returns Word 'Low' of a DWORD
HIWORD returns Word 'High' of a DWORD
SWAPBYTE switches bytes of a WORD
Shift SHL Shift left
SHR Shift right
Bit manipulation Bit to read a bit a analog value
SetBit to write the bit of an analog value
PackBits to put bits in an analog register
SplitBits to extract bits from an analog register
Trigger TriggerPos to work on the positive edge of a digital Tag
TriggerNeg to work on the negative edge of a digital Tag
Chrono PutChrono to force the writing of a value into chrono
Various Truncate to extract an Integer from a Float
Odd to indicate whether a Tag in Even or Odd
BCD to transform a decimal number to BCD format
Sampling Table Tablesize to check the size of a table
Samplebyte to access data of a Tag in ‘Byte’ format
Sampleword to access data of a Tag in ‘Word’ format
Sampledword to access data of a Tag in ’32 bits-Long’ format
Samplesingle to access data of a Tag in ’32 bits-Float’ format
Type Casting CBool Type casting to Boolean format
CByte Type casting to Byte format
CDWord Type casting to 32 bits-Long format (Unsigned)
CInt Type casting to Integer format (Signed)
CLng Type casting to 32 bits-Long format (Signed)
CSng Type casting to 32 bits-Float format
CWord Type casting to Word format (Unsigned)
Time GetRtuTime Copy the 3 ‘time’ variables in an atomic operation
GetRtuDate Copy the 3 ‘date’ variables in an atomic operation
Float isNaN To test if a float value is “Non a Number”
isINFinite To test if a float is INF or -INF
isZero To test if a float = 0
Random Rndm Compute a random value in a defined range

Version: 2.20 Page 32 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

INC
The INC function increments a variable (+1).

• Syntax
inc(Var)

• Argument
Var :must be any Integer variable: Byte, Word, Long

• Example
If TriggerPos(Pump_0) then
inc(Counter_0)
endif

DEC
The DEC function decrements a variable (-1)

• Syntax
dec(Var)

• Argument
Var :must be any Integer variable: Byte, Word, Long

• Example
If TriggerPos(Pump) then
dec(PumpActive)
endif

ABS
The ABS function returns the absolute value of any variable.

• Syntax
Result=abs(Var)

• Argument
Var :any format: Byte, Word, Long, Float

Version: 2.20 Page 33 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

LOBYTE
Returns the lowest Byte of a Word variable.

Example:

Variable: 0010010101101011

Result: 01101011

• Syntax
Result=LoByte(Var)

• Argument
Var :Word (16 bits)
Result :Byte or Word

HIBYTE
Returns the highest Byte of a Word variable.

Example:

Variable: 0010010101101011

Result: 00100101

• Syntax
Result=HiByte(Var)

• Argument
Var :Word (16 bits)
Result :Byte or Word

LOWORD
Returns the lowest Word of a DWord variable.

Example:

Variable: 00100101011010110010001100111101

Result: 0010001100111101

• Syntax
Result=LoWord(Var)

• Argument
Var :DWord (32 bits)
Result :Word

Version: 2.20 Page 34 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

HIWORD
Returns the highest Word of a DWord variable.

Example:

Variable: 00100101011010110010001100111101

Result: 010010101101011

• Syntax
Result=HiWord(Var)

• Argument
Var :DWord (32 bits)
Result :Word

• Example
HighestWord=HiWord(Long)

SWAPBYTES
Invert the bytes of a Word variable.

Example: inversion

Variable: 01111100 11000011

Result: 11000011 01111100

• Syntax
Result=SwapBytes(Var)

• Argument
Var :Word
Result :Word

Version: 2.20 Page 35 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

SHL
Shift to the left of x bits (without roll over).

Example: Shift left of 4

Variable: 00001111 00011000

Result: 11110001 10000000

• Syntax
Result=SHL(Var,shift)

• Argument
Var :Word or DWord
Shift :Word or Constant
Result :Word or Dword

Use the same format of Tag for Var and Result

SHR
Shift to the right of x bits (without roll over).

Example: Shift right of 4

Variable: 00001111 00011000

Result: 00000000 11110001

• Syntax
Result=SHR(Var,shift)

• Argument
Var :Word or DWord
Shift :Word or Constant
Result :Word or Dword

Use the same format of Tag for Var and Result

Version: 2.20 Page 36 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Bit
This function allows reading a bit in an analog register. The bit number starts at ‘bit0’ (lsb).

Example:

… 0 1 1 0 1 0 1 1

bit # ... 7 6 5 4 3 2 1 0

• Syntax
Result=Bit(Register, BitNumber)

• Argument
Result :Bool
Register :Word, DWord
BitNumber :Constant, Byte, Word, DWord

• Example
If bit(PumpList,4) then
Lamp4=1
endif

SetBit
This function allows forcing a bit in an analog register. The bit number starts at ‘0’ (lsb)

• Syntax
SetBit(Register, BitNumber, Value)

• Argument
Register :Word, DWord
BitNumber :Constant, Byte, Word, DWord
Value :Bool

• Example
'Inversion of bit 8.
Setbit(Register,8,not bit(Register,8))

Version: 2.20 Page 37 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

PackBits
These functions allow putting a series of addresses of digital Tags into an analog register.
There are 3 PackBits functions:

PackBits8: to put 8 Tags of successive addresses to a Byte register.


PackBits16: to put 16 Tags of successive addresses to a Word register.
PackBits32: to put 32 Tags of successive addresses to a DWord register.

• Syntax
Byte_register = PackBits8(Value)
Word_register = PackBits16(Value)
DWord_register = PackBits32(Value)

• Argument
Register : depending of the function it is a Byte, Word, or DWord
Value : it is the ModBus address of the first bit. The value at this address becomes the lsb of the
analog register

• Example
'Putting Digital DIR_0 to DIR_15 to register ANA_16
'ModBus address of DIR_0 = 20480

ANA_16 = PackBits16(20480)

DIR_0 0 1 1 1
DIR_1 0 1 0 1
DIR_2 0 1 0 1
DIR_3 0 1 0 1
DIR_4 0 1 0 1
DIR_5 0 1 0 1
DIR_6 0 1 0 1
DIR_7 0 1 0 1
DIR_8 1 0 0 1
DIR_9 0 0 0 1
DIR_10 0 0 0 1
DIR_11 0 0 0 1
DIR_12 0 0 0 1
DIR_13 0 0 0 1
DIR_14 0 0 0 1
DIR_15 0 0 1 1

ANA_16 256 255 32769 65535

1. When creating the digital Tags, be sure you reserve enough addresses after the
one declared in the function
2. Tags for all addresses do not need to be created, but it is advised to do it to avoid
confusion when creating Tags afterwards

Version: 2.20 Page 38 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

SplitBits
These functions allow extracting bits from an analog register to a series of ModBus addresses of digital Tags.
There are 3 SplitBits functions:

SplitBits8: extract the 8 bits of a Byte to 8 successive ModBus addresses of digital Tags.
SplitBits16: extract the 16 bits of a Word to 16 successive ModBus addresses of digital Tags.
SplitBits32: extract the 32 bits of a DWord to 32 successive ModBus addresses of digital Tags.

• Syntax
SplitBits8(Byte_register, Value)
SplitBits16(Word_Register, Value)
SplitBits32(DWord_Register, Value)

• Argument
Register : depending of the function it is a Byte, Word, or DWord
Value : it is the ModBus address of the first bit. The value at this address corresponds to the lsb
of the analog register.

• Example
'Extracting bits of ANA_16 to DIR_0 ... DIR_15
'ModBus address of DIR_0 = 20480

SplitBits16(ANA_16,20480)

ANA_16 256 255 32769 65535

DIR_0 0 1 1 1
DIR_1 0 1 0 1
DIR_2 0 1 0 1
DIR_3 0 1 0 1
DIR_4 0 1 0 1
DIR_5 0 1 0 1
DIR_6 0 1 0 1
DIR_7 0 1 0 1
DIR_8 1 0 0 1
DIR_9 0 0 0 1
DIR_10 0 0 0 1
DIR_11 0 0 0 1
DIR_12 0 0 0 1
DIR_13 0 0 0 1
DIR_14 0 0 0 1
DIR_15 0 0 1 1

1. When creating the digital Tags, be sure you reserve enough addresses after the
one declared in the function
2. Tags for all addresses do not need to be created, but it is advised to do it to avoid
confusion when creating Tags afterwards

Version: 2.20 Page 39 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Split32
This function converts one 32 bits register to two 16 bits registers.

This can be useful if you have to transfer 32 bits register, using a unique transaction including 16 bits and 32 bits registers.
The 32 bits registers will be seen as 2 x 16 bits registers.

• Syntax
Split32(32bitsReg, Hword, Lword)

• Arguments
32bitsReg : Register to split into 2 Words (DWord or Float)
Hword : High 16 bits of the 32 bits register (Word)
Lword : Low 16 bits of the 32 bits register (Word)

• Example
'Converting the Floating register Temperature to TempHigh and TempLow

Split32(Temperature, TempHigh, TempLow)

Pack32
This function converts two 16 bits registers into one 32 bits register.

• Syntax
Pack32(32bitsReg, Hword, Lword)

• Arguments
32bitsReg : Register receiving the 2 Words following (DWord or Float)
Hword : High 16 bits of the 32 bits register (Word)
Lword : Low 16 bits of the 32 bits register (Word)

• Example
'Converting the Temperature consisting of 2 Words

Pack32(Temperature, TempHigh, TempLow)

Version: 2.20 Page 40 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Trigger
The Trigger function allows checking a transition in an expression.

TriggerPos
It informs on the transition '0' to '1' of a digital Tag.

• Syntax
X = TriggerPos(expression)

X = 1 at changing of the expression (FALSE to TRUE) during one cycle of the program.

• Argument
X :Bool
Expression :any expression composed of Bool, Byte, Word, Long

• Examples
'To Set an Output when pressing a start button
if TriggerPos(Start) then
Output=1
endif

'To initialize a variable at start up of TBox MS


Dim Setpoint as Word
if TriggerPos(PrgRun!) then
Setpoint=123
endif

When the program starts, the internal status of the “TriggerPos” Function = 0.

Then, if the Tag associated to the Function = 1 when the program starts, the
function “TriggerPos” will be executed at the first cycle of the program, meaning
even if the Tag associated to the function has not changed from 0 -> 1.

If this can be an issue, the alternative is to use a flag instead of “TriggerPos” function:

If TriggerPos (MyTag) then Output=1

Becomes:

If TriggerPos (PrgRun!) then Flag=MyTag

If (Flag=0) And (MyTag=1) then


Output=1
Flag=1
endif

If (Flag=1) And (MyTag=0) then


Flag=0
endif

Version: 2.20 Page 41 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

TriggerNeg
It informs on the transition '1' to '0' of a digital Tag.

• Syntax
X = TriggerNeg(expression)

X = 1 at changing of the expression (TRUE to FALSE) during one cycle of the program.

• Argument
X : Bool
Expression : any expression composed of Bool, Byte, Word, Long

• Example
'To Reset an Output when pressing a Stop button
if TriggerNeg(Stop) then
Output=0
Endif

PutChrono
This function forces recording into the chronology.
Depending on the type of the Tag selected, the value is written to the ‘Analog chronology’ or ‘Digital chronology’.

• Syntax
PutChrono(variable)

• Argument
variable : Tag to insert into the chronology
digital Tag (Bool) → writing to Digital chronology
analog Tag (Byte, Word, Long, Single) → writing to Analog chronology

• Examples
if Button=1 then
PutChrono (Button)
PutChrono (Level)
PutChrono (Temperature)
Endif

Version: 2.20 Page 42 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Truncate
This function extracts the whole number from a Tag in Single format.

• Syntax
Long_register=Truncate(Single_register)

• Argument
Long_register : Long
Single_register : Single

• Examples
Whole_value = Truncate(Floating_reg)
If Floating_reg = 123.456 then Whole_value = 123

Odd
This function indicates whether an analog Tag is ODD or EVEN.

• Syntax
Bool_register=odd(analog_register)

• Argument
Bool_register : Bool
analog_register : Byte, Word, Long, Single

• Examples
Output=odd(Analog)
If Analog is ODD, Output=1; otherwise Output=0

BCD
This function transforms a decimal number to BCD format.
BCD format means that each 4 bits is considered as an entity corresponding to 1 number.

• Syntax
Word_output=bcd(Word_input)

• Arguments
Word_output : Word
Word_input : Word

• Examples
Output=bcd(Word)
If Word=4660 then Output=1234:
decimal: 4660
binary: 0001 0010 0011 0100
BCD 1234

Version: 2.20 Page 43 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Sampling tables
These functions allow accessing a specific value in a sampling table. They let you benefit from pre-computed values in a
sampling table, as illustrated in the example below:

• Syntax
tablesize(index) to check the size of a table
samplebyte(index,offset) to access data of a Tag in Byte format
sampleword(index,offset) to access data of a Tag in Word format
sampledword(index,offset) to access data of a Tag in 32 bits format
samplesingle(index,offset) to access data of a Tag in Float format

• Arguments
index: index of the sampling table (see list of sampling tables)
offset: sample you want to access. Offset=0 means the last sample

• Examples
Imagine you want to calculate the arithmetic average of a value based on a period of 15 minutes. You could do
it using Ladder or BASIC. But you can make it much more easily using a sampling table and one of those functions.

Sampling table configuration:


– Type= average
– period= 15 minutes
– Size= 1

You then use the function appropriate to the format of the Tag as follows:
Average=sampleword(1,0)

Version: 2.20 Page 44 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Type Casting
TWinSoft handles type casting automatically, but in some cases it can lead to misinterpretation.

To prevent it, we have implemented Type Casting functions that make you be sure of the type used in the Functions.

• Syntax
CBool(Var) Type casting to Boolean format
CByte(Var) Type casting to Byte format
CDWord(Var) Type casting to DWord format
CInt(Var) Type casting to Integer format
CLng(Var) Type casting to Long format
CSng(Var) Type casting to Single (Float) format
CWord(Var) Type casting to Word format

• Examples

Without Casting With Type Casting Function

Imagine A=1 (as a BOOL):

(A * 3600) is interpreted as (1 * 1 ) !! (CInt(A) * 3600) → (1 * 3600)


Type casting must be applied to the constant A is used as an Integer and not a Boolean

Imagine A=65535 (as a WORD)


Imagine B as a INTEGER

B=Abs(A) the result will be –1 !! B=Abs(CInt(A)) the result will be 1


Abs(65535) → 65535 Abs(-1) → 1
65535 in INTEGER format becomes -1

Version: 2.20 Page 45 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

GetRTUTime, GetRTUDate
You can use the system variables ‘Time’ (Hour, minute, second, …) to synchronize events from BASIC programming.

The risk is that handling several of those variables in one statement may lead to confusion.
Example:
If(Hour=6) And (Minute=0) And (Second=0)...

It is possible that the time changes during the test.

To avoid this situation, we have implemented a dedicated function to retrieve time using an atomic operation (all
operations without interruption)

• Syntax
GetRtuTime(MyHour, MyMinute, MySecond)
GetRtuDate(MyDay, MyMonth, MyYear)

• Arguments
Myxxx: Byte, Word (internal variables)

• Example
Sending an e-mail every day at 6:00 AM

GetRtuTime(MyHour, MyMinute, MySecond)


SendMail=((MyHour=6) And (MyMinute=0) And (MySecond=0))

Version: 2.20 Page 46 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Float Functions
As of TWinSoft 12.4 and OS 1.46, those functions allow testing the value of a float.

It can be out of range when it is “Not a Number”, when the binary sequence is not supported, or “Infinite”.

• Syntax
Test=isNaN(Var)
Test=isInfinite(Var)
Test=isZero(Var)

• Arguments
Test: Bool (0=False, 1=True)
Var: Single

• Example
Test_NAN=isNaN(MyFloat1)

• Additional data
There are 2 initialization data that can be applied to a Float variable through BASIC only: INF and -INF

• Syntax
Var=&PINF MIND it is case sensitive !
Var=&NINF MIND it is case sensitive !

• Example
MyFloat1=&PINF

Version: 2.20 Page 47 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Random Functions
As of TWinSoft 12.4 and OS 1.46, this function computes a random value in a range defined between a minimum and a
maximum value.

• Syntax
Var=Rndm(Min, Max)

• Arguments
Var: DWord
Min, Max: DWord

• Example

Version: 2.20 Page 48 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Text Functions
Text Functions are dedicated to BASIC, even if in some case, Text Tags can be used in Ladder (like in comparison functions).

Text Functions can be used in any type of POU (Program, FB or F) and when used in FB or F, 'Text' arguments are supported
in BASIC as well as in Ladder.

It is no possible to call a function within a function.


Example: Cat=("ABCD",CStr(123))
Instead, you have to use each function separately:
Temp= CStr(123)
Cat=("ABCD",Temp)

n=Len (T) returns the length (n) of the Tag Text T


if (T1 = T2) returns true if Tags Text T1 and T2 are identical, otherwise false.
if (T1 < T2) returns true if Tag Text T1 is lesser than T2., otherwise false
Comparison stops at the first difference between characters
if (T1 > T2) returns true if Tag Text T1 is greater than T2, otherwise false.
Comparison stops at the first difference between characters
T1 = T2 Copies Tag Text T2 to T1.
To copy a text directly to T1, use the double quotes.
Example: T1="ABCDEF"
T3 = Cat(T1, T2) Concatenates Text Tags T1 and T2 into T3.
n = CBool (T) returns a BOOLEAN (n) corresponding to the number found at the start of Text (T)
n = CByte (T) returns a BYTE (n) corresponding to the number found at the start of Text (T)
n = CInt (T) returns an INTEGER (n) corresponding to the number found at the start of Text (T)
n = CWord (T) returns a WORD (n) corresponding to the number found at the start of Text (T)
n = CLng (T) returns a LONG (n) corresponding to the number found at the start of Text (T)
n = CDWord (T) returns a DWORD (n) corresponding to the number found at the start of Text (T)
n = CSng (T) returns a SINGLE (n) corresponding to the number found at the start of Text (T)
T = CStr (n) creates a Text Tag T corresponding to the given number n. Type is implicit and
corresponds to the one of the Tag or constant n.
T = CHex(n) creates a Text Tag T of hexadecimal character representing the number n. Type is
implicit and corresponds to the one of the Tag or constant n.
T2 = LCase(T1) converts the whole text T1 to lower case in T2
T2 = UCase(T1) converts the whole text T1 to upper case in T2
i = InStr(T1, T2) returns position i of the first occurrence of T2 in T1, and -1 if no occurrence
T2 = Left(T1, n) extracts to T2 a substring of n characters from the beginning of T1
T2 = Right(T1,n) extracts to T2 a substring of n characters from the end of T1
T2 = Mid(T1, i, n) extracts to T2 a substring of n characters from the position i in the middle of T1
First character corresponds to i=0
StrToAscii(T1,pointer,n) converts the text of T1 into a series of consecutive byte registers
pointer=Tag with the ModBus address of the first byte
n= number of character to convert
T1=AsciiToStr(pointer,n) converts a series of consecutive byte registers into the Text Tag T1
pointer=Tag with the ModBus address of the first byte
n= number of character to convert
n=StrToIP(T) converts the dotted IP address in T (string or Text Tag) into a DWord (n)
T=IPtoStr(n) converts the DWORD (n) into a dotted IP address in a Text Tag (T)

Version: 2.20 Page 49 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Timers / Counters

See sections 3 and 4

Indirect addressing
Indirect addressing allows accessing Variables from their addresses (and not from their Tag name)

It can be in most of the case replaced by 'index addressing' and For...Next...Step statement which is typically used in
BASIC programming.

According to the type of Function used (Bool, Word, Float or Long), be careful to
associate addresses of similar registers.

Reading functions
• Syntax
Digital=PeekBool (Pointer) 'Reading at the address of a Tag BOOL
Analog16=PeekWord (Pointer) 'Reading at the address of a Tag WORD
Float=PeekFloat (Pointer) 'Reading at the address of a Tag FLOAT
Analog32=PeekLong (Pointer) 'Reading at the address of a Tag LONG
Text=PeekText (Pointer) 'Reading at the address of a Tag Text

• Arguments
Pointer : Word register containing the ModBus address of the variables.
Digital : Boolean variable to receive the status at the address of 'Pointer'.
Analog16 : 16 bits variable to receive the value at the address of 'Pointer'
Float, Analog32 : We advise to use a type of variable equivalent to the one of the addressread (Float when
addressing a Float, Long when addressing a Long, …)
Text : Text Tag to receive the text at the address of ‘Pointer’

Writing functions
• Syntax
PokeBOOL(Pointer, State)
PokeWord(Pointer, Value)
PokeFloat(Pointer, Value)
PokeLong(Pointer, Value)
PokeText(Pointer, Text)

• Arguments
Pointer :Word register or Expression containing the ModBus address of the variables.
State :Value (0 or 1) to write in the address of 'Pointer'
Value :Value or Expression to write in the address of 'Pointer'
Text :Text to write in the address of 'Pointer'. Can be a Text Tag of a String

Version: 2.20 Page 50 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Initialization of a Pointer
This function allows you to get the address of a Tag. It can be useful to initialize a Pointer from the first Tag that has to be
treated by the indirect addressing functions.

• Syntax
Pointer=AdrOf(Tag)

Note about ‘Address of’ function


The function Adrof(Tag) is particularly useful when working with addresses into Function or Function Blocks (see
sections 1.22 and 1.23)

Working with Function or Function Block, if you need the ModBus address of an input argument, you will have first to
extract it using BASIC Function Adrof(Tag) (see above).

Working with the former TBox (CPU-3), the ModBus address of the argument is passed to the Function or Function block.

Working with TBOX MS, TBOX LT2 or TBOX LITE, the value of the Tag is passed to the Function or Function block (in
fact, the argument is copied into an intermediate variable. Then the link with the real Tag is lost).

Example in the Function ‘SendAsciiFrame’ of the TEXT driver.

GOTO
• Label
A label can be defined anywhere in a program as follows:

Alarms:
Pumps:

The colon " : " indicates it is a label. The name of a label must use the following rules:
• characters accepted are letters, numbers and underscore.
• the name cannot start with a number.
• the maximum length is 15 characters.
• BASIC is not case sensitive.

To avoid confusion, do not use keywords (see section 1.19) or Tag names.

• Syntax
Goto Label

Version: 2.20 Page 51 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Keywords
BASIC uses the following keywords. You should not use names similar to those keywords.

% (modulo) LoByte
_ (underscore = break line) Log
Long
Abs LoWord
AdrOf Ln
And
ArcCosine Mid
ArcSine
ArcTangent Next
As Not
AsciiToStr
Odd
Bcd Or
Bit
Byte PackBit
PeekBool
Call PeekFloat
Cat PeekLong
CBool PeekWord
CByte Pow
CDword PutChrono
CHex
CInt Right
CLong Rem
Cosine Rndm
CountDown
CountUp Samplebyte
CountRing Sampleword
CountReset Sampledword
CSng Samplesingle
CStr SetBit
CWord Shl
Shr
Dec Sine
Dim Single
DWord SplitBit
Sqrt
Else Step
Elseif StrToAscii
Endif StrToIp
Exp SwapByte

For Tablesize
Tan
GetRTUTime Then
GetRTUDate TimerSS
Goto TimerMS
TimerIN
HiByte TimerOD
HiWord TimerReset
Integer To
TriggerNeg
If TriggerPos
Inc Truncate
InStr
IpToStr Xor
IsInfinite
IsNaN UCase
IsZero
Wend
LCase While
Len Word
Left
Let

Version: 2.20 Page 52 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU
According to IEC1131-3 standard, the programs are organized in POU, which stands for

‘Program Organization Unit’

In order to organize the programming, 3 types of POU are available.

Programs gives you the possibility to divide your project into several sub-programs (pump
management, alarms, intrusion, ...)
Each sub-program is POU Program.

Functions gives you the possibility to create your own function.


It is a piece of program leading to one result. Useful when there are
repetitive calculations.

Function Blocks gives you the possibility to create your own 'applet' or procedure (starting a
pump, regulating temperature).

It is a piece of program composed of input and output arguments. Useful when


the same process is applied to different sets of I/O (eg. Management of a pump
in an application handling 4 pumps).

Recursion is authorized but not for Function Block (A function cannot call itself):
1. We do not advise you use recursion
2. It is under your own responsibility

Version: 2.20 Page 53 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU – Program

Introduction
The POU “Programs” can be considered as sub-programs. They allow you to structure your BASIC project into several sub-
programs.

Practically, you have a BASIC program ‘main’, which calls sub-programs. These sub-programs correspond to an action such
as: start pump, intrusion control, alarms management etc..., and can be called from ‘main’ or any other sub-program.

This architecture gives you a clear view of the whole project.


The Programs can be tested individually, and it makes changing easier.

A Program can call another Program that can call another Program etc...

If you use Programs that call other Programs, be careful to avoid loops: Programs 1
calling Program 2 calling Program 3 that calls Program 1.

The Program 'Main'


The program 'main' is the root program. It must be unique and called ‘main’. It is used to call other Programs (sub-
programs).
It is the default program when starting a new TWinSoft document.
The program ‘Main’ supports LADDER or BASIC language.

While editing, it is possible to enter another POU directly from a program:

You select the name of the POU, press <CTRL> and double-click the name.

Changing language of ‘Main’

To change the language of ‘Main’, right click the name ‘Main’, go to Properties and change language to BASIC

Version: 2.20 Page 54 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Creating a Program
To create a Program, click the 'Programs' folder in the Project Workspace.

In the window appears the list of existing POUs (all types of POU). When starting TWinSoft the first time, the only one is the
'main'.

Double click 'Add a POU', type a Name (No accent, space or keywords (see section 1.19)) and check the type 'Program'.

Select language BASIC

Click OK.

You have created a Program and it appears in the 'Programs' folder.

When you double click the name of the Program in the list, the window for BASIC edition appears with a new Tab for the
current program.

Calling a Program
A Program can be called from any other Program. It is important that finally, it is called from the 'Main' Program.

• Syntax
To call a Program, use the syntax:

call Alarms 'Alarms is the name of the POU Program

The instruction Call is optional.

Version: 2.20 Page 55 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU – Function

Introduction
A Function is a user-defined program that executes a calculation yielding to one result (an output). It is useful when a
calculation you regularly need to execute does not exist as Standard functions. You call it in Programs every time you need
to execute the calculation. It has one or several inputs and only one output. When a Function is used many times in a
Program, the same code is always executed; one cannot keep trace of internal status between 2 calls.

According to the type of the output, there are 4 types of Functions:


➢ BOOL :Boolean output.
➢ WORD :analog output 16 bits.
➢ LONG :analog output 32 bits.
➢ FLOAT :Floating point output.

Inputs can be digital (Boolean) or analog.


Timers cannot be defined in a Function.

Creating a Function
To create a Function, click the 'Programs' folder in the Project Workspace.

In the window appears the list of existing POUs (all types of POU). When starting TWinSoft the first time, the only one is the
'main'.

Double click 'Add a POU', type a Name (No accent, space or keywords (see section 1.19)) and check the type 'Function'.
Select the language BASIC
Select the type of the output (result of the calculation): BOOL, WORD, LONG or FLOAT.
Click OK.

You have created a Function and it appears in the 'Programs' folder.

Version: 2.20 Page 56 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

When you double click the name of the Function in the list, the window for BASIC edition appears with a new Tab for the
current program.

Example of Function

The following Function is an analog Function (it means the output is analog). It performs the percentage of an input value.

• The Tags
When creating a Function, TWinSoft automatically creates the 'Output' Tag. It is the unique Output allowed.

'Inputs' and 'Outputs' of the Function are the arguments that will be replaced when calling the Function (see next).

You create then the 'Inputs', corresponding to the arguments of the Function.

Be careful with the 'type' associated to the arguments.


If you need 'local' Tags, you can create them from the list, or using the DIM statement.

The way a POU Function works, involves that one can define only local Tags in a
POU Function.

Percent:
the output of the Function. It is unique and is the result of the calculation.
MAX, MIN, VAL:
are the Inputs of the Function.
Delta, scale:
local analog Tags used as temporary variables necessary to calculate the percentage.

Global Timer and Counters are allowed in Function, but it is very uncommon and
against logic.

Version: 2.20 Page 57 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

• The programming
You use BASIC language for programming.

The column ‘Value’ in the list of POU Tags cannot be used.


It displays random values.

To check the Tags, look in the ‘list of Tags’ to the global Tags associated to the
arguments.

Calling a Function from a Program


A Function is called from a Program

• Syntax
Result=Function(Arg1, Arg2, Arg3, ...)

• Arguments
the Tag receiving the result of the Function
Result
the name of the Function
Function

Arg the input arguments (Tags or constant)

The Arguments have to be entered in the order they have been created in the list of
Tags of the Function.

Example:

Arg1 = Input

Arg2 = MIN

Arg3 = MAX

....

Example

'Call of Function: output=Percent(max,min,input)


AIR0 = Percent(maximum, minimum, ana_0)

POU Functions can be exported to a Library to be used in other TWinSoft


documents, using the Library manager menu (see section 5: ‘The library manager’)

Version: 2.20 Page 58 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU – Function Block

Introduction
Function Blocks are user defined small 'applets', or procedures that perform a set of operations on a given set of I/Os (or
registers).

Function Blocks are particularly helpful when the same set of operations must be performed on several different sets of I/Os,
figuring instances of a small process.

eg.: The TBox needs to handle 4 identical pumps. No need to copy the same program 4 times. You call a Function Block from
a Program every time you need to execute the process and you assign Tags to it.

We advise you against using Functions in a Function Block. In fact, a Function exists only once and uses always the same
internal variables when it is called.

A Function Block uses new Tags (local and global) every time it is called from a Program.

Creating a Function Block


To create a Function Block, click the 'Programs' folder in the Project Workspace.

In the window appears the list of existing POUs (all types of POU). When starting TWinSoft the first time, the only one is the
'main'.

Double click 'Add a POU', type a Name (No accent, space or keywords (see section 1.19)) and check 'Function Block'.
Select the language BASIC.
Click OK.

You have created a Function Block and it appears in the 'Programs' folder.

When you double click the name of the Function Block in the list, the window for BASIC edition appears with a new Tab for
the current program.

Version: 2.20 Page 59 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Example of Function Block

The following Function Block performs the start of a digital output with a programmable delay.
This Function Block implementation describes the inputs and outputs involved in the management of the delay. It also
specifies how long the delay is applied to the output.

It does not specify which Tags are physically connected to the ‘delay’: this is the job of the FB calling in a program (see
below).

• The Tags
Inputs and Outputs of a Function Block are the arguments to be replaced when calling the Function Block.

You create then the 'Inputs' and 'Outputs' in the list of POU Tags of the Function Block.

If you need 'local' Tags, you can create them from the list, or using the DIM statement.

INPUT is a digital input that will activate the OUTPUT after the DELAY.
OUTPUT is a digital output. It will be connected to a motor, for instance when calling the Function Block.
is an analog input containing the number of seconds of the delay. It must be associated to the
DELAY
timer used in the Function Block.
Timer0 is a local timer.
value is a local digital Tag of the type 'Timer - Value'.
status is a local digital Tag of the type 'Timer - Status'.
Timer_preset is a local analog Tag of the type 'Timer - Preset'.

Version: 2.20 Page 60 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

• The programming
You use BASIC language for programming.

Calling a Function Block in a POU Program


• Instantiation
A Function Block can be called several times, and for each call TWinSoft allocates new Tags.

The Instantiation allows TWinSoft to distinguish each call.

The Instantiation is done using a POU 'local' Tag. - From the Program where you wish to call the Function Block:
- In the list of POU Tag, click Add a POU Tag
- Type a name as Tag (the instance name)
- Select as ‘Type’ : FB Instance
- Select as ‘Name’ the name of your Function Block
- Click OK
- The instance appears in the list of ‘POU Tag’.

Example of Instantiation:

• Syntax
Call Instance(Arg1, Arg2, Arg3, ...)

The instruction Call is optional

Version: 2.20 Page 61 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

• Arguments
Instance the name given to the local Tag used as Instantiation

Arg the input arguments (Tags or constant)

The Arguments have to be entered in the order they have been created
in the list of Tags of the Function Block

Example

'The function block [Start_w_Delay] activates an output after a entered 'delay in


seconds; Arguments: (Input,Delay,Output).

call Motor1(DI_4, 6, DO_3, COUNT)

POU Functions can be exported to a Library to be used in other TWinSoft


documents, using the Library manager menu (see section 5: ‘The library manager’)

Version: 2.20 Page 62 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Programs - Ladder
TBOX MS, TBOX LITE, TBOX LT2 and TBOX NANO support 2 languages:

BASIC and Ladder.

Both languages are used to execute process automation

➢ BASIC is a text language, very easy to use for making calculation.


It supports all advanced mathematical functions.

➢ LADDER is a graphical language, which should be preferred when Boolean operations are required. LADDDER is
much more efficient than BASIC for handling ‘digital’ Tags.

BASIC and LADDER can be used together


We suggest that you divide your process into several programs ( sub-programs) depending on the process concerned.
According to the kind of process, you create programs in BASIC and programs in LADDER.

Then you combine programs, as you want: BASIC calling LADDER and reciprocal.

This section explains how to program in LADDER.

To see an example, load the TWinSoft document 'MSLadder.tws' that you find in the 'Samples' directory
of TWinSoft.

Sequence of Tasks of the process


The same as with BASIC (see section 1.1)

Version: 2.20 Page 63 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Ladder – Principle
The principle of the Ladder diagram is based on an electrical description of the process or machine, using relay logic. To the
left of the screen are the inputs (they are conditions for which an action will be undertaken) and to the right are the outputs
(which result from these actions).

Inputs
All inputs, whether digital or analog, can be combined to create logical equations:

<AND> using several inputs on the same line

<OR> using several inputs one above each other.

All analog comparison functions and/or digital inputs on the same program line will represent true or false. The result
defines the actions of the output (will or will not be performed).

The different types of Input conditions are accessible in the LD Toolbar.

Outputs
Digital output functions are engagements (SET relay) or disengagement (RESET relay), they can be the image or the
opposite of the result of the tested input conditions (OUTPUT relay and NEGATIVE relay). Other functions have been
introduced proper to telemetry like transmission of alarms, data logging, … To process analog variables, many
mathematical functions and POU (Program Organization Units) functions have been implemented, but you might find
easier to use BASIC for making calculation (see section1: BASIC)

The selection of different types of Output is accessible in the LD Toolbar.

Example of Ladder

Version: 2.20 Page 64 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Cycle time
The same as with BASIC (see section 1.2.6.)

Ladder - Modes

Introduction
The Ladder programming operates in two different modes.

The first is display mode, which allows you to see the entire program, one page at a time. It is in this mode that you can see
the state or the value of variables in real time.

The second mode is edit mode, which allows inserting a new line anywhere in the Ladder, at the beginning, at the end or
between two existing lines. This mode also allows modifying an existing line.

To see an example program, open the TWinSoft document ‘MSLadder.tws’ from the directory ‘Samples’ of TWinSoft.

Display mode
To access the Ladder in Display mode, click in the Project Workspace on the 'Programs' folder. The last Ladder that was
opened is displayed. The white tab underneath indicates the active program. The tab 'MAIN' is the main program, which is
automatically executed by the RTU; the other POUs having to be called from the ‘MAIN’.

The Ladder diagram is drawn in red lines with the Tags associated at each input contact, output relay or IN/OUT of
functions.

The Comment lines appear as gray blocks.

When a jump (JUMP) is programmed, the jump’s mnemonic appears at the right side of a double arrow. The mnemonic is a
LABEL that appears in black text.

A call to another program appears in a red block with one IN/OUT line.

The state of the Boolean objects (input contacts, analog comparison, output relays) is displayed as a green overlay if the
condition represented by the contact is true (in the case of a trigger input contact, the result represents the current state of
the Tag.

When moving the cursor on analog Tags in Functions or Math blocks, the current value is displayed in the bottom left corner
of the screen. For digital Tags the display indicates <On> or <Off> according to the current value.

Version: 2.20 Page 65 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Edit mode
The Edit mode is used when inserting a new line or modifying an existing line.

To insert a line, use the LD Toolbar. Three types of lines can be inserted using the following buttons:

to insert a line of Ladder

to insert a line of Comment

to insert a Label that will be called by a JUMP

The Ladder diagram is made of several lines that are numbered starting at 1. Only one line at a time can be edited with only
one rung (a rung is a set of Input conditions connected to only one set of Outputs). When editing is finished, the line must be
compiled to proceed with the next one:

To save and compile a line. If an error occurs, a dialog box informs you on the error. The key <+>
can also be used to save and compile a line.

If you were editing an existing line, you return to display mode.

If you were inserting a new line, you stay in edit mode.

To quit editing and discard changes. The key <ESC> can also be used.

To select any item (line, contact, relays or Functions) of a Ladder line. Once selected it can be edited
by a double click to replace Tags. You can also erase the selected item by pressing the key <Delete>
or insert a new contact, relay or Function by selecting the proper icon in the LD Toolbar.

Inserting a new line as last line


To insert a new line as last line, place the cursor at the end of the last line and click the icon corresponding to the type of line
you wish to insert.

Inserting a new line between 2 existing lines


To insert a line between 2 existing lines, place the cursor on the existing line that the new line will correspond to. The new line
will move the existing line to next position after it is inserted. When a line is selected, it is surrounded. Then click the icon
corresponding to the type of line you wish to insert. The line you placed the cursor on will be moved downwards. Using the
keyboard UP and DOWN arrows moves the selected line.

Modifying an existing line


To modify an existing line, place the cursor on the line you wish to modify. Then double-click it. The arrow icon of the LD
Toolbar is automatically selected.

Version: 2.20 Page 66 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Ladder - Toolbar
The LD Toolbar is the panel of tools necessary to edit Ladder. Different icons are active according to the current mode of
Ladder:

Display mode
Clicking one of the following icons lets you enter in the edit mode:

To insert a line of Ladder.

To insert a line of Comment.

To insert a Label that will be called by a JUMP.

Edit mode
To Select any item (line, contact, relays or Functions) of a Ladder line. Once selected it can be
edited by a double click to replace Tags. You can also erase the selected item by pressing the key
<Delete> or insert a new contact, relay or Function by selecting the proper icon in the LD Toolbar.

To Save and Compile a line. If an error occurs, a dialog box informs you of the error. The key <+
>can also be used to save and compile a line.

To Quit editing and discard changes. The key <ESC> can also be used.

To insert a Normal input contact for digital input. The condition will be true if the input is active.

To insert an Invert input contact for digital input. The condition will be true if the input is inactive.

To insert a Positive input trigger for digital input. The condition will be true only once when the
input passes from an inactive level to an active level.
Read important note at section 1.14.17

To insert a Negative input trigger for digital input. The condition will be true only once when the
input passes from an active level to an inactive level.

To insert a Digital output normal. Output is activated if the results of the input condition(s) are
true.

To insert a Digital output inverted. Output is activated if the results of the input condition(s) are
false.

To insert a Digital output set. Output is set and memorized if the result of the input condition(s)
are true; this type of output is typically used with a 'trigger' input

Version: 2.20 Page 67 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

To insert a Digital output reset. Output is reset and memorized if the result of the input
condition(s) are true; this type of output is typically used with a 'trigger' input

To draw continuous horizontal or vertical lines. To join inputs conditions together to create logical
equations and to possibly connect too many outputs.
WARNING: a set of inputs can only lead through one horizontal line to only one set of outputs. It
is called a rung.

To insert a Program, Function or Function Block. A list opens with the standard Functions (under
the folder 'Standard') and with the user defined Programs, Function and Function Block (under the
folder 'This file')

To insert a Mathematical block. In this block, mathematical functions can be inserted by clicking
on 'New Math Function'.

See the list of available functions in section 2.10.

Initiates a Jump to the line whose label corresponds to the one that is entered here (to enter a
label, see above in the list of icons of 'Display mode').

Variables

Introduction
Variables can be physical I/O, internal variables: analog (AIV) or digital (DIV) and system variables.

A variable becomes available when it is declared as a Tag. According to the use we make of the variables in Ladder
programming, there are two families of Tags:
➢ Local Tags
➢ Global Tags

Local Tags
A Local Tag is a non-specific register used as temporary value in a calculation. When compiling the TWinSoft document a
free memory zone (DIV or AIV) is assigned to it according to its type.

Local Tags are only used in the POU where they have been created.

They appear in the list of Local Tags, above the Ladder diagram of the POU (see next).

Global Tags
A Global Tag can be of two types:
- A specific variable (DIV, AIV, system variable, communication variable) that you wish to use.
- A physical I/O of the RTU created in the List of Tags.

Global Tags can be used in any POU Program and Function Block (see next).

Version: 2.20 Page 68 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

The Colors of the Tags


The color used to display the Tag in Ladder programming informs you of its type:
➢ Black: Global Tag.
➢ Blue: Local Tag.
➢ Brown: System variable (analog or digital). It is always considered as Global Tag

Create Ladder Diagram

Introduction
Creating Ladder diagram consists of 'drawing' program lines with input contacts or functions and output relays or functions
placed between 2 vertical Power Rails. The two rails can be considered as electrical wires between which items are placed.
The lines as a whole represents your local automation.

In the LD Toolbar click - - to insert a new Ladder Line. In the window of Ladder programming, a rectangle appears with
a line number. Only one line at a time can be edited with only one rung (a rung is a set of Input conditions connected to
only one set of Outputs). The grid shows you the places where you can place contacts, relays and functions.

The Ladder is executed from left to right and from top to bottom.

Each input is read before executing the Program and the value stored to be used all along the Program.

In the same way, each output is saved and executed only at the end on the Program.

Be careful when using an output at different places in the Program, unless you do SET and RESET. To help you, check the
Cross reference of the Tags.

According to the item you wish to use, select the proper icon in the Toolbar.

To get used to ladder programming, go to sections:


2.7. Step by step creating of ladder
2.8. Drawing lines in ladder…

Version: 2.20 Page 69 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Inserting items
When inserting an item, you must declare the variable(s) associated to it: Digital Tag for a contact and a relay, Digital or
Analog Tags for Functions.

You have to work with Tags.

A Tag (local or global) can be created while inserting an item.

There are two possibilities to select a Tag:

- You know the name of the Tag: you type its name. TWinSoft is not case sensitive, so
you can type it in capital or small letters.

The Tag exists - You don’t know the name of the Tag: you click the button to open the list of Tags.
You have the choice between Global Tag, Local Tag and System variables (see
previous section ‘Variables’).

You type its name and press <ENTER> to create it. The Tag can be either Local Tag or
The Tag does not exist Global Tag (see previous section ‘Variables’).

According to the field you are in, you can select a Tag (digital or analog) or directly type a
constant.
Check the title of the insertion window; it informs you on what you can use.

The colors of the Tags


See section2.5.3 above.

The Keys

<+> To compile a line. Similar to the icon

- When a line is selected: to quit edit mode. Similar to the icon


<ESC> - When an item is selected: to release the item and return to selection mode (arrow).
- When Tag box is opened: to carry on without specifying a Tag. '???' will be inserted instead. To
enter a Tag afterwards, double click '??? '

<DEL> To delete the selected item.

Version: 2.20 Page 70 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Step by step creating of Ladder


We assume that Tags already exist and that we work with global Tags.
Suppose we are controlling a Reservoir LEVEL. When it reaches the value 150, we start the PUMP to remove water. At the
same time, we start a Timer INTEGRAL that memorizes the number of minutes the pump has been working.
The PUMP can also be started manually.
When 100 hours are reached (360000 seconds), the status of the timer changes to 1 and activates the output
MAINTENANCE.

We will create the following lines:

We use the following Tags (see the corresponding TBox manual section: Tags):
Level analog input (Float)
Manual digital input.
Pump digital output.
Timer_Status digital internal variable associated to the timer ‘Qty_minutes’
Maintenance digital output.
Reset digital input.

List of Tags in TWinSoft

List of Timers in TWinSoft

Version: 2.20 Page 71 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

If you encounter difficulties in drawing lines, go to section 2.8. Drawing Lines in Ladder…

1st line of Ladder:

1. In the program ‘MAIN’, click the icon to insert a line of comment. Type you text and click ‘OK’.

2nd line of Ladder:

2. Click the icon to insert a new line. The edit block is ready to create the second line. The grid shows the position
where you can place the items.

3. Click the icon to insert the function A>B and then click next to the left Rail.

4. Enter the Tag LEVEL or select it from the list of Tags and then enter the constant 150.

5. Click the icon to insert a digital contact, then click below the comparison Function close to the left rail.

6. Enter the Tag MANUAL or select it from the list of Tags.

7. Click the icon and draw a horizontal and vertical line to join the output of the comparison Function.

8. Click the icon to insert an output relay, then click on the output of the comparison Function. A horizontal line
including the relay is automatically drawn to the right rail.

9. Enter the Tag PUMP or select it from the list of Tags.

Version: 2.20 Page 72 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

10. Click the icon , go to the folder ‘Timers’ and select the timer Integral (TI).

11. Type the name of the Timer (instance name), or if it exists, you can browse it from the button

12. Type the Preset of 360000 (= 100 hours). Preset is always expressed in seconds.

13. Click the icon and draw a horizontal and vertical line to join the timer Function to the right rail and to the output of
the comparison Function.

14. Press the key <+>, or click the icon to compile the line. Doing this, the edition block is ready to create the third line.

3rd line of Ladder:

15. Click the icon to insert a Positive edge trigger contact, then click next to the left rail.

16. Enter the Tag TIMER_STATUS.

17. Click the icon to insert a SET output relay, then click next to the right side of the contact TIMER_STATUS. A
horizontal line including the relay is automatically drawn to the right rail.

Version: 2.20 Page 73 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

18. Enter the Tag MAINTENANCE or select it from the list of Tags.

19. Press the key <+>, or click the icon to compile the line. Doing this, the edition block is ready to create the fourth
line.

4th line of Ladder:

20. Click the icon to insert a Positive edge trigger contact, then click next to the left rail.

21. Enter the Tag RESET or select it from the list of Tags.

22. Click the icon to insert the reset timer Function, then click next to the contact RESET.

23. Type the name of the Timer or select it from using the browse button .

24. Click the icon and then click the reset timer Function; drag it one step to the right.

25. Click the icon and draw a horizontal line between the RESET contact and the reset timer Function.

26. Click the icon to insert a output relay associated to the Tag MAINTENANCE, then click under the reset timer
Function. A horizontal line is automatically drawn to the right rail.

27. Enter the Tag MAINTENANCE or select it from the list of Tags.

28. Click the icon and draw a horizontal and vertical line to join the input contact to the output relay MAINTENANCE.

29. Press the key <+>, or click the icon to compile the line. Doing this, the edition block is ready to create the next line.

30. Press <ESC> to return to Display mode.

Version: 2.20 Page 74 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Drawing lines in ladder ….


You might find difficulties in drawing line, then it is important you understand the rules:

• To draw a line, you drag the cursor until the end of the line segment.
• You draw horizontal and vertical line after each other.
• With the cursor inside a cell, the line is drawn when you cross to the next cell.

Select the tool ‘Line’ from the LD toolbar

Place the cursor inside the cell and maintain the


left button of the mouse …

… drag the mouse to the right. When you cross


to the cell next, a black line appears…

…when you have reached the end of the


horizontal line, release the button. The line
changes to red color.

To continue, at the cursor position maintain the


left button of the mouse …

… drag the mouse to the bottom. When you


reach the bottom of the cell a black line
appears…

…when you have reached the end of the vertical


line, release the button. The line changes to red
color.

To continue, at the cursor position maintain the


left button of the mouse …

… drag the mouse to the right. When you


cross to the cell next, a black line appears…

…when you have reached the end of the


horizontal line, release the button. The
line changes to red color.

That’s it !

Version: 2.20 Page 75 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Functions
Ladder provides a series of pre-defined functions to perform operations like Comparisons, Assignment, Boolean
operations,.…

Ladder provides also Timer functions (for counting time) and Counter functions (for counting pulses).

Almost all functions have the 2 connections:

- EN: Enable Input: Connection to the Ladder line. EN must be TRUE to perform the Function.

- ENO: Enable Output: it is the image of EN. If EN is TRUE, ENO is TRUE. It can be connected to
a contact or a relay, a Mathematical block or another Function.

To insert a Function, in the edit mode of Ladder Programming, click the icon of the LD Toolbar.

The functions are divided into several folders:

Version: 2.20 Page 76 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Analog Comparison Functions


Those functions represent input conditions used to carry out comparisons between 2 analog variables.

The output is TRUE when the input values fit with the comparison, otherwise it is FALSE. The output can be connected to a
relay, a Math Block, another Function or a POU. The parameters are:

- EN: Connection to the Ladder line. EN must be TRUE to perform the Function.

- A, B: Inputs : analog Tags (Byte, Word, Long or Float) or constant.

- OUT: Digital Output of the Function: TRUE when A & B fit with the Function selected and EN is
TRUE.
It can be connected to a relay, a function or a mathematical block

When ana0 is equal to ana1, OUT is TRUE

When ana0 is smaller than ana1, OUT is TRUE

When ana0 is larger than ana1, OUT is TRUE

When ana0 is smaller than or equal to ana1, OUT is TRUE

When ana0 is larger than or equal to ana1, OUT is TRUE

When ana0 is different to ana1, OUT is TRUE

Special Functions

Writing of the digital Tag 'dig0' in the Digital Chronology.

Writing of the analog Tag 'ana0' in the Analog Chronology.

Version: 2.20 Page 77 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Timer & Counter Functions

See sections 3 and 4

Math. Assignments functions


The parameters are:

- A: Input : analog Tag or constant.

- Q: Output : analog Tag of the Function.

Q = A: the Tag 'anaOUT' contains a copy of the value of the Tag anaIN'

Q = -A: the Tag 'anaOUT' contains the inverse value of the Tag 'anaIN'

Q = low(A): the Tag 'anaOUT' contains a copy of the 8 lowest bits of the Tag
'anaIN'
A and Q must be WORD

Q = high(A): the Tag 'anaOUT' contains a copy of the 8 highest bits of the Tag
'anaIN'
A and Q must be WORD

Q = abs(A): the Tag 'anaOUT' contains a copy of the absolute value of the Tag
'anaIN'
A and Q must be WORD

High-LowQ = Low-HighA: the Tag 'anaOUT' contains the inversion of the 8


highest bits and the 8 lowest bits of the Tag 'anaIN'
A and Q must be WORD

in(A): increase by 1 bit the Tag 'anaIN'.

dec(A): decrease by 1 bit the Tag 'anaIN'.

Version: 2.20 Page 78 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Math. Arithmetic functions


The parameters are:

- A, B: Inputs : analog Tags (Byte, Word, Long or Float) or constant.

- Q: Output : analog Tag (Byte, Word, Long or Float).

The Tag 'anaOUT' is the addition of the Tags 'ana0' and 'ana1'

The Tag 'anaOUT' is the subtraction of the Tags 'ana0' and 'ana1'

The Tag 'anaOUT' is the multiplication of the Tags 'ana0' and 'ana1'

The Tag 'anaOUT' is the division of the Tags 'ana0' and 'ana1'

The Tag 'anaOUT' is the rest after the division of the Tags 'ana0' and 'ana1'.
Example: 2 = 17 MOD 3

Math. Bitwise functions


The parameters are:

- A, B: Inputs : analog Tag (Word only) or constant.

- Q: Output : analog (Word only) or digital Tag, according to the Function.

- Bit: Input : digital Tag of the Function

- Index: Input : constant between 0 and 15

- Word: Input or Output : analog Tag, according to the Function

'anaOUT' is the result of the logical AND between 'ana0' and 'ana1'
Example: 0001000011111111
AND 0001100000001111
0001000000001111

'anaOUT' is the result of the logical OR between 'ana0' and 'ana1'


Example: 0000000011111111
OR 1111000000001111
1111000011111111

Version: 2.20 Page 79 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

'anaOUT' is the result of the logical XOR between 'ana0' and 'ana1'
Example: 0000000011111111
XOR 1111000000001111
1111000011110000

The status of digital Tag 'dig0' will be copied in the analog Tag 'anaOUT' at the
position indicated by the Index.
Example: dig0: 1
Index: 3
anaOUT: 0011010011001001

The status of the bit of the analog Tag 'ana0' indicated by the Index will be
copied in the digital Tag 'digOUT'.
Example: ana0: 1100101000010010
Index: 5
dig0: 0

Math. Shift functions


The parameters are:

- IN: Input : analog Tag. It is a Word or a Byte according to the Function

- Bit: Constant : number of bits to shift

- Q: Output : analog Tag (Word) of the Function

Wraparound means that the bits scrolling out from one side of a Byte (8 bits) or Word (16 bits) are copied at the other side
of the byte or word.

'anaOUT' has the number of 'Bit' shift to the left (max. 15) of the Word analog
Tag 'ana0'
(without wraparound).

'anaOUT' has the number of 'Bit' shift to the right (max. 15) of the Word analog
Tag 'ana0'
(without wraparound).

'anaOUT' has the number of 'Bit' shift to the left (max. 7) of the Byte analog Tag
'ana0'
(with wraparound).

'anaOUT' has the number of 'Bit' shift to the right (max. 7) of the Byte analog
Tag 'ana0'
(with wraparound).

'anaOUT' has the number of 'Bit' shift to the left (max. 15) of the Word analog
Tag 'ana0'
(with wraparound).

'anaOUT' has the number of 'Bit' shift to the right (max. 15) of the Word analog
Tag 'ana0'
(with wraparound).

Version: 2.20 Page 80 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Mathematical Block
A mathematical Block allows carrying out analog output operations like assignment, arithmetic operations, comparisons,
Boolean operation, indirect addressing, …

When calculations are concerned, we advise the use of BASIC; being a text language, you
may find it more user-friendly.

Another reason is that advanced mathematical functions are only available with BASIC
(SIN, COS, POWER, …)

To insert a Math block, in the edit mode of Ladder Programming, click the icon of the LD Toolbar.

Introduction
There are 7 categories of mathematical functions available (to use in math blocks):
• Assignments
• Arithmetic operations.
• Comparisons.
• Bit manipulations.
• Boolean Operations.
• Conversion + Indirect addressing.
• Miscellaneous.

In the functions, the Arguments to be replaced by Tags (or constants) are represented as follows:

- A, B, C, and D Analog Tags.


Depending on the functions the Tags can be:
- When combining different formats of Tags (Byte, Word, Long, Float),
check the rule of type casting (see section 1.9.1).
- Limited to Byte or Word (obvious according to some functions like
Rotation, conversion of 16xBool to a Word, …)
- Ptr Pointer
Doing indirect addressing, it is an Analog Tag
- BOOL Digital Tag

An assignment operation is always executed from the right to the left. In other words, we have: result = operation

Which means: output = input (meaning the value of Input variable is copied in the Output variable).

To insert a 'Math function' between 2 existing functions in a Math block, edit the line, place the cursor at the position you
want to insert the function, and press the key <Insert> of keyboard.

Version: 2.20 Page 81 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Type Casting
Read information about Type Casting section 1.9.1.

Assignments
A = B 'A' contains a copy of the value of 'B'
A = -B 'A' contains the inverse value of 'B'
A = Low(B) If B is a WORD: 'A' contains a copy of the 8 lowest bits of 'B'
If B is a LONG: 'A' contains a copy of the 16 lowest bits of 'B'
A = High(B) If B is a WORD: 'A' contains a copy of the 8 highest bits of 'B'
If B is a LONG: 'A' contains a copy of the 16 highest bits of 'B
A = Abs (B) 'A' contains a copy of the absolute value of 'B'
A = Swap(B) 'A' contains the inversion of the 8 highest bits and the 8 lowest bits of 'B'
Examples: B = 256 (00000001 00000000)
A=1 (00000000 00000001)
inc (A) increase the value of Tag 'A' by 1 unit
dec (A) decrease the value of Tag 'A' by 1 unit

Arithmetic operations
A = B + C 'A' is the addition of 'B' and 'C'
A = B - C 'A' is the subtraction of 'B' and 'C'
A = B * C 'A' is the multiplication of 'B' and 'C'
A = B / C 'A' is the division of 'B' and 'C'
A = B * C / D 'A' is the result of the multiplication of ‘B’ and ‘C’, divided by ‘D’.
Particularly useful to execute scaling with one function.
A = B AND C 'A' is the result of the logical AND between 'B' and 'C'
Example: 0001000011111111
AND 0001100000001111
0001000000001111
A = B OR C 'A' is the result of the logical OR between 'B' and 'C'
Example: 0000000011111111
OR 1111000000001111
1111000011111111
A = B XOR C 'A' is the result of the logical XOR between 'B' and 'C'
Example: 0000000011111111
XOR 1111000000001111
1111000011110000
A = B MOD C 'A' contains the rest after the division of 'B' and ‘C’.
Example: 2 = 17 MOD 3

When doing logical operations, check you don’t work with Float variable.
There is no linear sequence in the binary format of Float register, like with Word or Long.

Version: 2.20 Page 82 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Comparisons
BOOL = B == C 'BOOL' is TRUE if 'B' equal 'C', otherwise it is FALSE
BOOL = B < C 'BOOL' is TRUE if 'B' is smaller than 'C', otherwise it is FALSE
BOOL = B > C 'BOOL' is TRUE if 'B' is greater than 'C', otherwise it is FALSE
BOOL = B <= C 'BOOL' is TRUE if 'B' is smaller than or equal to 'C', otherwise it is FALSE
BOOL = B >= C 'BOOL' is TRUE if 'B' is greater than or equal to 'C', otherwise it is FALSE
BOOL = B <> C 'BOOL' is TRUE if 'B' and 'C' are different, otherwise it is FALSE
BOOL = odd B 'BOOL' is TRUE if the value of 'B' is odd, otherwise it is FALSE

Bit manipulations
Wraparound means that the bits scrolling out from one side of a byte (8 bits) or word (16 bits) are copied at the other side of
the byte or word.
bit (A,BitNb) = BOOL The status of digital 'BOOL' will be copied in the analog 'A' at the position
indicated by 'BitNb', starting with ' 0 ' for Lsb.
Example: Bit: 1
BitNb: 3
A: 0011010011001001
BOOL = bit( A,BitNb) The status of the bit of the analog 'A' indicated by 'BitNb' will be copied in
the digital 'BOOL', starting with ' 0 ' for Lsb.
Example: A: 1100101000010010
BitNb: 5
Bit: 0
A = shl(B,shift) 'A' has the number of Bits indicated by 'shift' shift to the left (max. 15) of
the Word 'B'
(without wraparound).
Example: B: 0000000011111111
Shift: 4
A: 0000111111110000
A = shr(B,shift) 'A' has the number of Bits indicated by 'shift' shift to the right (max. 15) of
the Word 'B'
(without wraparound).
Example: B: 0000000011111111
Shift: 4
A: 0000000000001111
A = rol byte(B,shift) 'A' has the number of Bits indicated by 'shift' shift to the left (max. 7) of
the Byte 'B'
(with wraparound).
A = ror byte(B,shift) 'A' has the number of Bits indicated by 'shift' shift to the right (max. 7) of
the Byte 'B'
(with wraparound).
A = rol word(B,shift) 'A' has the number of Bits indicated by 'shift' shift to the left (max. 15) of
the Word 'B'
(with wraparound).
Example: B: 0000000011111111
Shift: 4
A: 0000111111110000

Version: 2.20 Page 83 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

A = ror word(B,shift) 'A' has the number of Bits indicated by 'shift' shift to the right (max. 15) of
the Word 'B'
(with wraparound).
Example: B: 0000000011111111
Shift: 4
A: 1111000000001111

Boolean operations
BOOL = not(BOOL) the inverse of the digital Tag of the right is assigned to the digital Tag of
the left
BOOL = BOOL AND BOOL the result of the logical AND between the two digital Tags of the right is
assigned to the digital Tag of the left
BOOL = BOOL OR BOOL the result of the logical OR between the two digital Tags of the right is
assigned to the digital Tag of the left
BOOL = BOOL XOR BOOL the result of the logical XOR between the two digital Tags of the right is
assigned to the digital Tag of the left

Conversion + Indirect addressing

A = bcd(B) transforms the Word 'B' to a BCD format and transfers the result to the Word
'A'. 'B' must be of maximum 39321 (corresponding to 9999) to prevent an
overflow condition.
BCD format means that each 4 bits is considered as an entity corresponding to
1 number.
Example:
binary: 0001 0010 0011 0100
BCD 1234
decimal: 4660
A = 16 x (BOOL) places the 16 digital variables of successive addresses, starting with the
digital Tag 'BOOL' in the Word' A'.
Example:
to copy 16 digital inputs of an extension card in a word.
WARNING: when using this function, check that there are 16 successive
ModBus addresses, starting from the Tag ‘BOOL’
16 x (BOOL) = A places the 16 bits of the Word 'A' in the 16 digital variables of successive
addresses, starting with the digital Tag 'BOOL'.
Example:
to SET or RESET 16 DO of an extension card using an analog variable.

When using the two above functions, check that there are 16 Tags with successive
ModBus addresses, starting from the Tag ‘BOOL’

Version: 2.20 Page 84 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

A = FloatToInt (Flt * 10 E Const) conversion from the Float 'Flt' to the Integer 'A' , with a
possible scaling from 10E-4 to 10E+4. The exponent must
be a constant:'Const'.
Flt = IntToFloat (A) * 10 E Const conversion from the Integer 'A' to the Float 'Flt', with a
possible scaling from 10E-4 to 10E+4. The exponent must
be a constant:'Const'.
BOOL = indirect (Ptr) the Tag or Constant 'Ptr' contains the ModBus address of the digital variable
that will have its status assigned to the digital Tag 'BOOL'.
Example:
to read the status of an output 'Q0' having ‘32’ as ModBus address:
DIV0 = indirect (Pointer). (Pointer = 32)
Indirect (Ptr) = BOOL the status of the digital Tag 'BOOL' will be copied in the digital variable whose
ModBus address is defined in the Tag or Constant 'Ptr'.
Example:
to write the status of DIV0 to the output 'Q2' having ‘34’ as ModBus address:
Indirect (Pointer) = DIV0. (Pointer = 34)
A = indirect (Ptr) the Tag or Constant 'Ptr' contains the ModBus address of the analog variable
that will have its value assigned to the analog Tag 'A'
Example:
to read the value of the input 'ana0' having 64 as ModBus address:
AIV0 = indirect (Pointer). (Pointer = 64)
indirect (Ptr) = A the value of the analog Tag 'A' will be copied in the analog variable whose
ModBus address is defined in the Tag or Constant 'Ptr'.
Example:
to write the value of ‘ana0’ to the analog output having as ModBus address
288:
Indirect (Pointer) = ana0. (Pointer = 288)

Miscellaneous
Adr = Tag (Tag) Gives you the ModBus address of the ‘Tag’.
Number between 1 and 65535 (see note below)
put Bit in dig chrono Writing of the digital Tag 'Bit' in the Digital Chronology.
put A in ana chrono Writing of the analog Tag 'A' in the Analog Chronology.

Version: 2.20 Page 85 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Note about ‘Adr=Tag(Tag)’ function


This function is particularly useful when working with addresses into Function or Function Blocks (see sections 2.13 and 2.14)

Working with Function or Function Block, if you need the ModBus address of an input argument, you will have first to
extract it using Math. Function Adr = Tag(Tag) (see above).

Working with the former TBox (CPU-3), the ModBus address of the argument is passed to the Function or Function block.

Working with TBOX MS, TBOX LITE, TBOX LT2 and TBOX NANO, the value of the Tag is passed to the Function or
Function block (in fact, the argument is copied into an intermediate variable. Then the link with the real Tag is lost).

Example with Function ‘SendAsciiFrame’ of TEXT driver

Version: 2.20 Page 86 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU (Program Organization Units)

IEC1131-3 Ladder programming is organized not only with contacts and relays, but also with different POUs and functions.

Three types of POU are available, all of which use the same Ladder programming tools and BASIC instructions:

List of POU

POU program: sub-program that is called in the ‘Main’ program or any other POU program.

POU function: standard functions (comparison, math. Functions, timers,...) or user defined functions.

POU function block: user defined small 'applet' that performs a function (start of a pump, regulating
temperature...)

Recursion is authorized but not for Function Block (A function block cannot call itself):
1. We do not advise you use recursion, because of cycle time issue.
2. It is under your own responsibility

Version: 2.20 Page 87 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU – Program

Introduction
POU programs allow you to structure your Ladder program into several sub-programs.

In practice, you have a main Ladder program, which calls sub-programs. These sub-programs contained within a Ladder
diagram precisely define an action such as; start pump, intrusion control, alarms management...etc, and can be called from
anywhere in the ‘Main’ program or any other POU program.

They give you a clearer view of the whole automation program, they can be tested individually and allow you to make
things easier for changing.

A POU program can call another POU Program that can call another POU Program etc...

If you use POU Programs that call other POU Programs, be careful to avoid loops: like Program 1 calling Program 2 calling
Program 3 that calls Program 1.

The Program 'Main'


The program 'main' is the root program. It must be unique and called ‘main’. It is used to call other Programs (sub-
programs).

It is the default program when starting a new TWinSoft document.

The program ‘Main’ supports LADDER or BASIC language. It can be changed at the condition the program is empty. Right
click ‘main’, select ‘Properties’ and choose a language.

Creating a POU Program


To create a POU Program, click the 'Programs' folder in the Project Workspace. In the right window appears the list of
existing POUs (all types of POU). When starting TWinSoft the first time, the only one is the 'main'.

Version: 2.20 Page 88 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Double click 'Add a POU', type a Name (No accent, space or keywords (see BASIC)) and check 'Program'.

Select the language ‘Ladder’

Click OK.

You have created a POU Program and it appears in the 'Programs' folder.

When you double click the name of the Program in the list, the window for Ladder programming appears with a new Tab for
the current Program.

Now you can create a Ladder Diagram for the Program you have defined.

Version: 2.20 Page 89 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Calling a POU Program in another Program

To call a POU Program, click the icon in the LD Toolbar. In the folder, 'This File' select the POU Program you wish to
insert. All POU Programs have the following parameters:

- EN: Enable Input: Connection to the Ladder line. EN must be TRUE to run the Program. If it is
connected directly to the left rail, it will be executed at each cycle of the Ladder, otherwise it
can be connected to an input condition.

- ENO: Enable Output: it is the image of EN. If EN is TRUE, ENO is TRUE. It is usually connected to
the right rail but can be also connected to a contact or a relay, a Mathematical block or a
Function.

Calling a POU Program is like calling a sub-routine. The program associated to it is executed at the position where it is
called.

Version: 2.20 Page 90 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU – Function

Introduction
A POU Function is a user-defined piece of Ladder that executes a calculation ending in one result. It is useful when a
calculation you regularly need to execute does not exist in the list of Standard Functions. You use it in POU Programs every
time you need to execute the calculation. It has one or many inputs and only one output. When a Function is used many
times in a POU Program, the same code is always executed.

Example:

You need regularly to execute the calculation: y= [(a+b) * (c+d)] /2.

You will not find this formula in the Standard Functions or in the Mathematical Function block. You will then create your
own Function that will execute your calculation every time you call it.

According to the type of the output, there are 4 types of Functions:


• BOOL: digital output.
• INT: analog 16 bits output.
• LONG: analog 32 bits output.
• FLOAT: floating point output.

Restriction
• Do not use global Tags in a Function.
• Do not use global Timers and Counters in a Function.
• Do not use output relay SET and RESET. Because the same internal code is used for each call of the function
and then the SET or RESET status will be applied at each call of the function.

Example
An example of user defined Function is available in the TWinSoft document ‘Ladder.tbox’, in the 'Samples' directory of
TWinSoft. The Function executes the scaling of an 8-bit analog input.

Version: 2.20 Page 91 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Creating a POU Function


To create a POU Function, click the 'Programs' folder in the Project Workspace. In the right window appears the list of
existing POUs (all types of POU). When starting TWinSoft the first time, the only one is the 'main' POU Program.

Double click 'Add a POU', type a Name (No accent, space or keywords (see BASIC)) and check 'Function'.

Select the language Ladder

Select the type of the output (result of the calculation): BOOL, WORD, LONG or FLOAT.

Click OK.

You have created a POU Function and it appears in the 'Programs' folder.

When you double click the name of the Function in the list, the window for Ladder programming appears with a new Tab for
the current Function.

Version: 2.20 Page 92 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

1. By default, the name of the Output is the name of the Function. You can rename the
output by using the context menu on its name (mouse right clicking on the name).
2. POU Functions can be exported in a Library to be used in other TWinSoft documents,
using the Library manager menu

Now you can create Ladder Diagram for the Function you have defined.

Version: 2.20 Page 93 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Example of a Function
The following Function is an analog Function (it means the output is analog). It performs the percentage of an input value.

• The Tags :
When creating a Function, TWinSoft automatically creates the 'Output' Tag. It is the unique Output allowed.

Inputs and the Output of a Function are the arguments to be replaced when calling the Function.

 The way a POU Function works, involves that one can define only local Tags in a POU Function.

Percent: the output of the Function. It is unique and is the result of the calculation.

MAX, MIN, VAL: are the Inputs of the Function.

Delta, scale: local analog Tags used as temporary variables necessary to calculate the percentage.

• The Ladder :
A math block using 3 functions is used.

Global Timer and Counters are allowed in Function, but it is very uncommon and against
logic.

Version: 2.20 Page 94 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Calling a POU Function in a POU Program

To call a Function, click the icon in the LD Toolbar. The folder, 'This File' contains Functions and Function Blocks
created in the current document. If the Function owns to a Library, the latter appears as a Folder. Select the Function you
wish to insert. All Functions have the following parameters:

- EN: Enable Input: Connection to the Ladder line. EN must be TRUE to perform the Function. If it is
connected directly to the left rail, it will execute at each cycle of the Ladder, otherwise it can be
connected to an input condition.

Enable Output:
- ENO:
if the Function is Analog: it is the image of EN. If EN is TRUE, ENO is TRUE. It is usually
connected to the right rail but can be also connected to a contact or a relay, a Mathematical block
or another Function.
if the Function is Digital: ENO and the Output of the Function are linked inside the Function. It
is TRUE if the result of the calculation AND EN are TRUE. It must then be connected to contact
or a relay, a Mathematical block or another Function.

When calling the Function in a POU Program, you must assign a Tag to the (unique) Output, and a Tag or constant to each
input.

All inputs are at the left side of the Function; the output at the right side.

In this example, we wish to have the percentage of input ‘ANA_0’ in the range between 0 and 500.

Version: 2.20 Page 95 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

POU - Function block

Introduction
POU function Blocks are user defined small 'applets' that performs a function (start of a pump, regulating temperature...).
If this function is repetitive in your program and you don't wish to define it every time you need it, then you create it once as
a POU Function Block, with Input and Output arguments.

You call it in POU Programs every time you need to execute the function and you assign Tags of your program to the
arguments of the Function Block.

We advise you against using POU Functions in a POU Function Block. In fact, a POU Function exists only once and always
has the same variables that are used when inserting the POU Function.

A POU Function Block uses new resources (Tags, Timers, …) every time it is called in a POU Program.

Creating a POU Function Block


To create a POU Function Block, click the 'Programs' folder in the Project Workspace. In the right window appears the list of
existing POUs (all types of POU).

When starting TWinSoft the first time, the only one is the POU Program 'main'.

Double click 'Add a POU', type a Name (No accent, space or keywords (see BASIC)) and check 'Function Block'.

Click OK.

You have created a POU Function Block and it appears in the 'Programs' folder.

Version: 2.20 Page 96 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

When you double click the name of the Function Block in the list, the window for Ladder programming appears with a new
Tab for the current Function Block.

POU Function Blocks can be exported to a Library to be used in other TWinSoft


documents, using the Library manager menu (see section 5: ‘The library manager’)

Now you create Ladder Diagram for the Function Block you have defined.

Version: 2.20 Page 97 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Example of a Function Block


The following Function Block performs the start of a digital output with a programmable delay.

• The Tags:
Inputs and Outputs of a Function Block are the arguments to be replaced when calling the Function Block.

INPUT is a digital input that will activate the OUTPUT after the DELAY.
is a digital output. It will be connected to a motor, for instance when calling the Function
OUTPUT
Block.
is an analog input containing the number of seconds of the delay. It must be associated
DELAY
to the timer used in the Function Block.
Timer is a local timer.
Timer_preset is a local analog Tag of the type 'Timer - Preset'.
Timer_status is a local digital Tag of the type 'Timer - Status'.

• The Ladder :
• The DELAY is copied in the preset of the timer and multiplied by 1000 (the timer preset is expressed in
milliseconds).
• When INPUT changes to 1, it starts the timer Single Shot
• Note: when working with an external Preset (the local variable 'Timer_preset'), the Preset of the timer can be
set to any value; it is not used. Here = 0
• When the timer has finished counting AND INPUT is still active, the output is set.
• A negative edge on INPUT resets the OUTPUT.

Version: 2.20 Page 98 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Calling a POU Function Block in a POU Program

To call a Function Block, click the icon on the LD Toolbar. The folder, ‘This File’ contains Function Blocks and Functions
created in the current document. If the Function Block owns to a Library, the latter appears as a Folder. Select the Function
Block you wish to insert. All Function Blocks have the following parameters:

- EN: Enable Input: Connection to the Ladder line. EN must be TRUE to perform the Function Block. If it
is connected directly to the left rail, it will execute at each cycle of the Ladder, otherwise it can be
connected to an input condition.

- ENO: Enable Output: it is the image of EN. If EN is TRUE, ENO is TRUE. It is usually connected to the right
rail but can be also connected to a contact or a relay, a Mathematical block or another Function.

When Calling the Function Block in a POU Program, you are asked to enter an 'FB Instance name' (in this example ‘Motor1’).

This name allows TWinSoft to distinguish between Function Blocks, when multiple calls of similar Function Blocks are
defined.

Afterwards you must assign to the Output(s) and Input(s) Tags or constant. All inputs are at the left side of the Function
Block, all outputs at the right side.

In this example, the FB is called ‘Motor1’, the input ‘D0’ activate the output ‘Q2’ with a delay of 5 seconds.

Each call of Function Block is unique and different from each other; local Tags of the Function Block as well as timer and
counter, will be assigned to free registers, timers and counters when compiling.

1. A Function Block accepts maximum 16 Arguments.


2. There is no limit in the quantity of Timers and Counters used in a Function Block.

Version: 2.20 Page 99 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Debugging of a Function block


As explained above, the same piece of Ladder of the POU FB can be called several times (several instances).

In order to debug a function block, to check values and status of the local Tags, it is not sufficient to enter the code of the FB,
because TWinSoft needs to know which instance is concerned.

IMPORTANT:
1. The document must have been sent to TBox with the last changes
2. If TWinSoft is opened after the document has been sent, the document must be compiled, to allow TWinSoft
assigning registers to the local Tags.
3. The complete path from the Program 'main' must be followed to access the FB. Example: 'Main' -> 'Motors' -> FB
'Motor1'.

To debug the FB, while in 'Visualization mode', double click the call of the FB from the POU program in which it is used:

The source code (Ladder) of the FB is then opened and dynamized according to its instance.

In the list of POU Tags, the column 'Value' displays values of each local Tag.

Indirect addressing inside a Function Block


See section 2.10.8.

Version: 2.20 Page 100 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Timers

Presentation
Timers are used for counting a time, a delay.

• The maximum working time of 1 hour for a pump


• The control of the time a modem is connected
• The flashing of a lamp, using building a Flip-Flop with 2 timers
• A delay before starting a motor
• A delay before detecting an intrusion
• …

Counters are used for counting pulses (see section 4).


The mechanism of both functions is similar, the way they are used and the variable associated.

The difference is that when a timer has been launched, it runs on its own until a defined preset of time when a counter
increments every time it receives a pulse.

Timers can be used either with BASIC or Ladder programming.

When created, Timers and


Counters are available from the
Resources in a folder:

The List of Timers and the List


of Counters

The way of using timer in Ladder is discussed in section 3.5 and in BASIC section3.6.

Version: 2.20 Page 101 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Introduction
Four models of timers are available:

• Single Shot: time cycle resets on each input activation.


• MonoStable: time cycle does not reset until it is over.
• Integral: time cycle with accumulation.
• On Delay: time cycle without accumulation.

Each model is presented with a diagram in sections 3.8, 3.9, 3.10 and 3.11.

In theory, the quantity of timers is not limited. Practically, it is limited to 32767 !

For each timer (regardless of type), there are two analog variables and one digital variable associated with it:

• Preset: analog variable with the Timer Preset.


• Value: analog variable with the Timer Value.
• Status: digital variable, i.e. the logical state of the Timer.

These three variables can be assigned as Tags and used in the BASIC or Ladder diagram (example: an automatic
modification of a process at timed intervals).

To see an example of using Timers, load the document 'MSTimer.tws' that you find in the sub-directory of TWinSoft
'Samples'.

Creating a Timer

You create the Timers in the List of Timers, from the ‘Resources’

A Timer can also be created while editing a Ladder diagram, but for BASIC the Timer must be created before it can be
declared in a program.

From the ‘Resources’ and the list of Timers,


click ‘Add a Timer’

To edit an existing Timer, you double-click


it in the list.

Version: 2.20 Page 102 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

The variables of a Timer


Each Timer can be controlled using 3 variables:
• Preset: AIV in 32 bits DWord format (time in millisecond)
• Value: AIV in 32 bits DWord format (time in millisecond)
• Status: DIV as it indicates the timer is running or not.

Those variables are standard internal variables, with a free name. Once created in the list of Tags they can be associated to
a timer.

Probably status will need to be created, as it will be required to control the timer: timer still running or period elapsed.

Preset and Value are optional and only required if they need to be monitored from the process or from external software.

For example the Timer Fan1,


with 3 Tags associated:

Status of the Timer:

Value of the Timer:

Preset of the Timer:

1. Tags cannot be shared by several timers.


2. You don’t have to create a variable if you don’t need it.
3. Do not give the same name for ‘Timer’ and ‘Counter’ (see section 4)

When Tags are available, the current values appear in the list of Timers:

Version: 2.20 Page 103 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Saving Dynamic Preset


Imagine you have changed dynamically the Preset of the timer from a WebForm, a HMI, a SCADA, … When the program
starts, you expect it will start with the Preset as it was before.
But it will not; it will start with the preset defined in the call of the Timer function.
And you don't want to initialize the Tag, because you want to keep the value as it was before.

To keep Preset value when it has been changed, it has to be backed up and restored at start-up of TBox, like this:

If Triggerpos(PrgRun!) Then
If ((Preset_old <5000) Or (Preset_old >50000)) Then
Preset_old=10000 ‘for security if preset out of range
Endif
Preset=Preset_old
Endif

If (Preset <> Preset_old) Then


Preset_old=Preset
Endif

Using Timers in Ladder

To use a timer, you click the F/FB button

in the LD Toolbar and you select


from the Folder ‘Timers’ the type of timer
you need.

The Function ‘ResetTimer’


is used to reinitialize a
timer, depending on the
model (see below) or to
clear it before it has
reached its preset.

Once you have selected the type of timer, it appears in the Ladder line.

Example with a Timer Monostable (MS)

Version: 2.20 Page 104 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

The instance name


Any name, used as reference to the timer:

- If it has been previously created in the ‘list of timers’ (see below): you select it.

- If it does not exist: you type a name and TWinSoft prompts you to create it.

Example: Fan1

The Preset
A constant to indicate the time in seconds. This constant is in floating point with the decimal representing time smaller
than 1 second.

Examples:

0.50 = 500 ms.


7.50 = 7 sec. 500 ms.
900 = 15 minutes

The minimum preset and resolution are:


MS-CPU16: 10ms
MS-CPU32: 1ms
The character used to separate units from
decimals depends on your regional settings,
typically ‘ , ’ or ‘ . ’

Dynamic Preset

If you want to work with a dynamic preset, you will use a Tag (format DWord 32 bits) associated to the Preset (see section
3.4).

You still have to indicate a constant here, it will not be used but is mandatory when calling the function.

A Timer function is inserted to a ladder line as follows:

In Blue, its name (see instance name above).

Its Preset (see above).

EN Enable. It activates the timer function.

ENO Enable Output : it is the image of EN. If EN is TRUE, ENO is TRUE. It can be connected to a contact
or a relay, a Mathematical block or another Function.

If you want to clear a timer, you select the Function 'ResetTimer' associated to its name.

Version: 2.20 Page 105 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Using Timers in BASIC

Reminder
Four models of timer can be used in BASIC programs:
• Single Shot: fixed time and restartable
• MonoStable: fixed time not restartable
• Integral: measuring of a period with accumulation
• On Delay: measuring of a period without accumulation

Syntax
Single Shot: TimerSS (Name, Start, Preset)

MonoStable: TimerMS (Name, Start, Preset)

Integral: TimerIN (Name, Start, Preset)

On Delay: TimerOD (Name, Start, Preset)

• Arguments
Name : It is the name of the timer you have created (see section 3.3. above)

Start : INPUT Bool.

The Tag or expression that activates the timer.

Preset: INPUT. Constant giving the preset of the timer in sec. using a Floating register.

Example: 10.5 (= 10 seconds and 500 ms.)

To access other variables of a Timer (Status and Value), or to work with dynamic Preset, you have to create Tags and
associate them to the timer while creating it (see sections 3.3 and 3.4 above)

It is not possible to loop on timer arguments.

Example:
For i=4
TimerSS(name, start[i],Preset[i])

Version: 2.20 Page 106 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Reset Timer Function


A dedicated reset function can be used to re-initialize the timer (depending on the type of Timer. Please refer to the
diagrams in sections 3.8, 3.9, 3.10 and 3.11).

• Syntax
TimerReset (Name)

• Argument
Name : It is the name of the timer you have created (see section 3.3 above)

Examples
• How to manage time sequences using a Timer.

Upon a given event, one needs to start the following sequence:

- 1 minute after event, execute Prog1


- 5 minutes after event, execute Prog2
- 10 minutes after event, execute Prog3

You create a Monostable Timer from the list of Timers. You name it for instance MyTimer.

'The variable ‘Event’ is a digital input of the RTU


TimerMS(MyTimer,Event,1800)

if TriggerPos(Time>=60) then call Prog1


if TriggerPos(Time>=300) then call Prog2
if TriggerPos(Time>=600) then call Prog3

• Flip-Flop using 2 Single Shot Timers.

When you want to execute an operation alternatively on 2 devices, you can easily create the alternation with 2 Timers:
one starting the other.

It is possible to adapt the frequency of the Flip-Flop by changing dynamically the value of Tags ‘Preset1’ and ‘Preset2’.

You create 2 Single Shot Timers, each of them with a ‘Status’ Tag and a ‘Preset’ Tag.
You name the timers, for instance MyTimer1 and MyTimer2

'Flip-Flop using 2 Timer SS / 2.5 sec. ON and 2.5 sec. OFF

TimerSS (MyTimer1,not(Status2),2.5)
TimerSS (MyTimer2,not(Status1),2.5)

Using Timers in POUs


Timers are used differently in the different POUs:
Program: you use Global Timers (the ones you declare in the folder ‘Timers’)
Function: you cannot use Timer
Function Block: you use Local Timers (you declare them in the list of local Tags of the POU)

Version: 2.20 Page 107 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Coming in following sections, the presentation of each model of Timer with its
implementation in Ladder and a timing diagram.

Timer – Single Shot

Example of Ladder implementation

A rising edge on the Tag INPUT starts the timer for the PRESET time period (5sec.). The Tag STATE (which corresponds to
the digital state of the timer) changes to 1 as soon as a rising edge of the Tag INPUT appears and changes to 0 when the
PRESET time expires, or upon activation of a 'Reset Timer' Function associated with the timer.

If a new rising edge of the Tag INPUT appears before the end of the Preset time the cycle is re-started

Version: 2.20 Page 108 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Timer – Monostable

Example of Ladder implementation

A rising edge on Tag INPUT starts the timer for the PRESET time period (5sec.). The Tag STATE (which corresponds to the
digital state of the timer) changes to 1 as soon as a rising edge of the Tag INPUT appears and changes to 0 when the
PRESET time expires, or upon activation of the Timer Reset function associated with the timer.

If a new rising edge appears before the end of the PRESET time, it has no effect on the cycle

Version: 2.20 Page 109 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Timer – Integral

Example of Ladder implementation

Version: 2.20 Page 110 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

The Tag INPUT must remain at 1 for the duration of the time defined in PRESET, so that the Tag STATE (which reflects the
digital state of the timer) can change to 1. It remains active until the first rising edge of the Tag RESET (re-initialization the
timer).

If Tag INPUT falls to 0 before the end of the PRESET time, the value of the timer is retained (except if the rising edge of
the Tag RESET appears and resets the timer).

The re-activation of the Tag INPUT allows the timer continuing and completes the cycle.

To reinitialize the timer you need to use the ‘Reset Timer’ Function and reset Input=0

Version: 2.20 Page 111 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Timer – On Delay

Example of Ladder implementation

If the Tag INPUT remains at 1 for the duration of time defined in PRESET, the Tag STATE (which reflects the digital state of
the timer) changes to 1. This Tag returns to 0 as soon as INPUT changes to 0.

If INPUT is deactivated before the end of the time cycle, the value of the timer is reset to 0.

There is no accumulation.

The Tags of the timer are updated when the timer is scanned. It means that the precision
depends on the cycle time of the process.

Version: 2.20 Page 112 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Counters

Presentation
Counters are used for counting pulses

Counters are used for asynchronous event counting.

Timers are used for counting a time, a delay (see section 3)

• The maximum working time of 1 hour for a pump


• The control of the time a modem is connected
• The flashing of a lamp, using building a Flip-Flop with 2 timers
• A delay before starting a motor
• A delay before detecting an intrusion
• …

The mechanism of both functions is similar, the way they are used and the variable associated too.

The difference is that when a timer has been launched, it runs on its own until a preset when a counter increments every
time it receives a pulse.

Counters can be used either with BASIC of Ladder programming.

When created, Counters are available


from the Resources in a folder in the List
of Counters

The way of using counter in Ladder is discussed section 4.4 and in BASIC section 4.5.

Version: 2.20 Page 113 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Introduction
Three types of counters are available:

• Counter UP: Counts up


• Counter DOWN: Counts down.
• RING counter: Circular counter (it restarts itself when the Preset is reached.

Each model is presented with a diagram in sections 4.6, 0 and 4.8.

In theory, the quantity of counters is not limited. Practically, it is limited to 32767 !

For each counter (regardless of type), there are two analog variables and one digital variable associated with it:

• Preset: analog variable with the Counter Preset


• Value: analog variable with the Counter Value.
• Status: digital variable, i.e. the logical state of the Counter.

These three variables can be assigned as Tags and used in the BASIC or Ladder diagram (example: an automatic process at
intermediate values).

Creating a Counter
You create a Counter from the ‘list of Counters’.

A Counter can also be created while editing a Ladder diagram, but for BASIC the Counter must be created before it can be
declared in a program.

From the ‘Resources’ and the list of


Counters, click ‘Add a Counter’

To edit an existing Counter, you double-


click it in the list.

Version: 2.20 Page 114 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

The variables of a Counter


Each Counter can be controlled using 3 variables:
• Preset: AIV in 32 bits format (maximum number of pulses)
• Value: AIV in 32 bits format (current quantity of pulses)
• Status: DIV (it indicates the preset quantity of pulses has been reached).

Those variables are standard internal variables, with a free name. Once created in the list of Tags they can be associated to
a counter.

Probably Status will need to be created, as it will be required to control the counter: maximum number of pulses reached
or not.

Preset and Value are optional and only required if they need to be monitored from the process or from external software.

For example the Counter Pump1_hours,


with 3 Tags associated:

Status of the Counter:

Value of the Counter:

Preset of the Counter:

1. Be sure you create different variables for each counter. TWinSoft will prompt you
when you use a variable already used by another counter.
2. It is not needed to create a variable if you don’t need it.
3. Do not give the same name for ‘Counter’ and ‘Timer’ (see section 3)

When Tags are available, the current values appear in the list of Counters:

Version: 2.20 Page 115 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Using Counters in Ladder

To use a counter, you click the F/FB


button in the LD Toolbar and you
select from the Folder ‘Counters’ the
type of counter you need.

The Function
‘ResetCount’ is used to
reinitialize a counter,
depending on the
model (see next) or to
clear it before it has
reached the preset.

Once you have selected the type of counter, it appears in the Ladder line.

Example with a Counter UP

The contact used with the pulse input

It must be an ‘Edge’ contact (positive or negative edge contact)

The instance name


Any name, used as reference to the counter:
• - If it has been previously created in the ‘list of counters’ (see below): you select it.
• - If it does not exist: you type a name and TWinSoft prompts you to create it.

Example: Pump1_Hours

Version: 2.20 Page 116 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

The Preset
A constant to indicate the quantity of pulses to reach the end of counting. This constant is expressed in Dword format
(max. 4,294,967,296)

A Counter function is inserted to a ladder line as follows:

In Blue, its name (see instance name above).

Its Preset (see above).

EN Enable. Each pulse increments the counter with 1.

ENO Enable Output : it is the image of EN. If EN is TRUE, ENO is TRUE. It can be connected to a contact
or a relay, a Mathematical block or another Function.

If you want to clear a counter, you select the Function 'ResetCount' associated to its name.

Version: 2.20 Page 117 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Using Counters in BASIC

Reminder
Three types of counters are available:
• Counter UP: Counts up
• Counter DOWN: Counts down.
• RING counter: Circular counter (it restarts itself when the Preset is reached.

Syntax
CountUP (Name, Start, Preset)
CountDown (Name, Start, Preset)
CountRing (Name, Start, Preset)

• Arguments
Name : It is the name of the counter you have created (see section 4.2.1)

Start : INPUT Bool. The Tag or expression that increments the counter.

The ‘start’ input must be associated to a Trigger function (TriggerPos or TriggerNeg)

Preset: INPUT. Constant giving the preset in number of pulses.

Reset Counter Function


A dedicated reset function can be used to re-initialize the counter (depending on the type of Counter. Please refer to the
diagrams in sections 4.6, 0 and 4.8)

• Syntax
CountReset (Name)

• Arguments
Name : It is the name of the counter you have created (see section 4.2.1 above)

Using Counters in POUs


Counters are used differently in the different POUs:

Program: you use Global Counters (the ones you declare in the folder ‘Counters’)
Function: you cannot use Counter
Function Block: you use Local Counters (you declare them in the list of local Tags of the POU)

Coming in following section the presentation of each model of Counter with its
implementation in Ladder and a timing diagram.

Version: 2.20 Page 118 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Counter - UP

Example of Ladder implementation

Version: 2.20 Page 119 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Suppose that the Preset of the counter is 5. At each rising edge of the Tag PULSE, the value of the counter is incremented
with 1, and when it reaches the value of the Preset, the Tag STATE (which represents the digital state of the counter)
changes to 1.

The count continues until the Tag RESET is triggered, which resets the value of the counter.

At any given time, you can reset the counter with the help of the function CounterReset, activated in this example by the
Tag RESET.

You can pre-position the current value of the counter (using the Ladder diagram and the
variable associated to the value) if you do not want the counting to start at zero, but at
another value.

Version: 2.20 Page 120 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Counter - DOWN

Example of Ladder implementation

Version: 2.20 Page 121 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Suppose that the Preset of the counter is 3 and the variable associated to the value of the counter is initialized to 5 (Tag
COUNT). The latter has priority on the preset defined in the Counter function.

This operation can be done manually or by the Ladder diagram. In this example, it is the Tag INIT that initiates this
operation.

At each rising edge of the Tag PULSE, the value of the counter is decremented.

The Tag STATE (which represents the digital state) remains at 1 as long as the current value is greater than the pre-
selection.

When the current value becomes less than the pre-selection, the Tag STATE changes to 0 and the counting continues to 0.

Version: 2.20 Page 122 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Counter - RING

Example of Ladder implementation

Version: 2.20 Page 123 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Suppose that the Preset of the counter is 5.

At each rising edge of the Tag PULSE, the value of the counter is incremented, and when this value reaches the Preset
value, the Tag STATE (which represents the digital state) changes to 1.

During the next rising edge of the Tag PULSE, the value is set to 0.

A new counting cycle begins.

At any given time, you can reset the counter with the help of the function ResetCount, activated in the example by the Tag
RESET.

If the Tag RESET is associated to a ‘normal contact’, the counter is blocked until the contact opens again and releases the
counter (see notes below).

1. When working with counters, use positive or negative edges (pulse contact, push
button).
2. Do not drive more than once the same counter. If different input conditions are
necessary to increase (decrease) a counter, use those on the same Ladder line, and if
this is impossible, use a temporary digital variable to summarize all your conditions,
then declare this variable, to drive the counter.

Version: 2.20 Page 124 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Library Manager
TWinSoft offers the possibility to save POU Functions and POU Function Blocks in external files called ‘Libraries’ in order to
use those POU in other TWinSoft documents.

A library can contain several POUs.

Function and Function Blocks from both BASIC and Ladder are concerned

A library corresponds for instance to a customer or to a category of functions.

A library is a file with the extension .LIB, saved by default in the directory of TWinSoft.

POU Program cannot be saved.

Import of POUs (saving POUs in a Library)


To access the Import menu, click ‘Tools’ on the main menu bar and select ‘Library manager’

Only POU Functions and Function Blocks can be saved in a library:


1. You select an existing library (‘File’ → ‘Open’), or you create a new library (‘File’ → ‘New’).
2. You open the list of available POUs of the current document (‘Edit’ →‘Import POU...’).
3. You select the POU you wish to save in the Library; you repeat operations 2 and 3 for each POU.
4. You save the Library (‘File’ → ‘Save’).

Version: 2.20 Page 125 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Libraries can be protected by a password, so that it is impossible to ‘Export’ it into a


TWinSoft document, to see the internal code.

Export of POUs (retrieval of POUs from a library)


To access the Export menu, click ‘Tools’ on the main menu bar and select ‘Library manager’ (see import of POUs above).

Export is necessary if you wish to edit a POU in the current document that has been saved in a Library.

You open a library (‘File’ → ‘Open’); the POUs appear in the top window.

You select the POU and export it (‘Edit’ → ‘Export’); you repeat this operation for each POU.

The POUs are then available in the list of 'Programs', in the Project Workspace.

Use of a Library in a TWinSoft document


To access the 'Libraries' menu, click 'File' on the main menu bar and select 'Libraries...'

The ‘Available Libraries’ are the ones present in the directory of the current TWinSoft document or in the directory of
TWinSoft.

When a library appears in the list, all its POU Functions, and POU Function Blocks are available to be used in Ladder
programming: in the list of Functions, the Libraries appear as Folders, each containing their own POUs.

To add a Library to the current TWinSoft document, select it from the list of ‘Available Libraries’ and click ‘Add: →’.

When you have selected the library(ies) you need, click ‘Close’.

The button 'Manager' jumps to the creation of Library menu.

To remove a Library from the current TWinSoft document, select the Library and click 'Remove'. This operation is available
only if you don’t use POU of the concerned library in the current document.

Version: 2.20 Page 126 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Index

SetBit ............................................................................... 37
shift .................................................................................. 36
A Split32 .............................................................................. 40
Address of (function) ............................................................. 51 SplitBits ............................................................................ 39
Adr=Tag(Tag) function .......................................................... 86 square root ....................................................................... 31
Text Functions .................................................................. 49
trigger .............................................................................. 41
B trigonometry .................................................................... 29
Truncate ........................................................................... 43
BASIC ...................................................................................... 9 types of variable................................................................ 14
- (subtraction) ................................................................... 20 while...wend ..................................................................... 28
* (multiplication) .............................................................. 21 XOR .................................................................................. 24
/ (division) ......................................................................... 21
+ (addition) ....................................................................... 20
abs ................................................................................... 33 C
AND ................................................................................. 23
assignment ....................................................................... 13 Case....................................................................................... 10
BCD .................................................................................. 43 Colors
bit manipulation ................................................................37 BASIC ............................................................................... 10
byte manipulation ............................................................ 34 Ladder .............................................................................. 69
case .................................................................................. 10 Constant
colors ............................................................................... 10 BASIC .......................................................................... 10, 12
comment .......................................................................... 12 in timer (BASIC) .............................................................. 106
comparison....................................................................... 15 in timer (Ladder) ............................................................. 105
constant ........................................................................... 12 Counters ...............................................................................113
dec ................................................................................... 33 Down .............................................................................. 121
Dim .................................................................................. 14 in BASIC.......................................................................... 118
exponential....................................................................... 30 in Ladder ........................................................................ 116
Float functions .................................................................. 47 in POU ............................................................................ 118
for...next...step ................................................................. 26 Ring ................................................................................ 123
for...nextcycle ................................................................... 26 Up .................................................................................. 119
functions .......................................................................... 32 variables ......................................................................... 115
general ............................................................................. 10 Cycle
GetRtuDate ...................................................................... 46 sequence of tasks ................................................................ 9
GetRtuTime ...................................................................... 46 Cycle time ................................................................... 11, 12, 65
Goto ................................................................................. 51
if...then...else…elseif ........................................................ 16 G
inc .................................................................................... 33
indirect addressing ........................................................... 50 Goto ...................................................................................... 51
keywords ..................................................................... 10, 52
label ................................................................................. 51
line feed............................................................................ 10
I
logarithms ........................................................................ 30 Indirect Addressing ................................................................ 50
ModBus address function.................................................. 51 in BASIC............................................................................ 50
modulo ............................................................................. 22 Ladder .............................................................................. 84
NOT ................................................................................. 25
Odd .................................................................................. 43
OR .................................................................................... 24 K
Pack32 .............................................................................. 40
PackBit ............................................................................. 38 Keywords ..........................................................................10, 52
Peek ................................................................................. 50
Poke ................................................................................. 50 L
POU ................................................................................. 53
power ............................................................................... 31 Ladder ................................................................................... 63
precautions....................................................................... 12 arithmetic (math.block) .................................................... 82
putchrono ......................................................................... 42 arithmetic functions .......................................................... 79
Random............................................................................ 48 assignement functions ...................................................... 78
sampling tables ................................................................ 44 assignments (math.block) ................................................. 82

Version: 2.20 Page 127 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

bit manipulations (math.block) ......................................... 83 POU.................................................................................. 53, 87


Bitwise functions .............................................................. 79 Function ..................................................................... 56, 91
boolean operations (math.block) ...................................... 84 Function block ............................................................ 59, 96
color of Tags ..................................................................... 69 Function block debugging ............................................... 100
comparison (math.block) .................................................. 83 'main' .......................................................................... 54, 88
comparison functions ........................................................ 77 Program ..................................................................... 54, 88
conversions (math.block) .................................................. 84 Precautions ............................................................................ 12
create a rung .................................................................... 69 Program 'main' ................................................................ 54, 88
display mode ............................................................... 65, 67
drawing a line ................................................................... 75
edit mode ....................................................................66, 67
S
functions .......................................................................... 76 Sampling Tables
indirect addressing (math.block) ....................................... 84 BASIC functions ................................................................ 44
keys .................................................................................. 70 Sequence of tasks .................................................................... 9
mathematical block .......................................................... 81
miscellaneous (math.block) .............................................. 85
POU ................................................................................. 87 T
Shift ................................................................................. 80
special functions ................................................................ 77 Tags
step by step .......................................................................71 local, global ...................................................................... 68
toolbar.............................................................................. 67 Tasks sequence ........................................................................ 9
variables ........................................................................... 68 Text Functions ....................................................................... 49
Library Timer
use in TWinSoft document .............................................. 126 dynamic preset ............................................................... 104
Library manager .................................................................. 125 Timers ................................................................................. 101
export POU..................................................................... 126 in BASIC.......................................................................... 106
import POU .................................................................... 125 in Ladder ........................................................................ 104
in POU ............................................................................ 107
Integral ........................................................................... 110
M Monostable..................................................................... 109
On Delay ......................................................................... 112
Mathematical functions ......................................................... 29 Single Shot ..................................................................... 108
ModBus address function.................................................. 51, 86 variables ......................................................................... 103
ModBus addresses Trigger .............................................................................. 41, 67
as argument of F or FB ................................................. 51, 86 Type Casting .....................................................................18, 45

P W
Peek ...................................................................................... 50 Watchdog .............................................................................. 11
Poke ...................................................................................... 50

Version: 2.20 Page 128 of 129


BASIC & Ladder for TBox -MS, -LITE, -LT2, -Nano

Copyright © 2022 Ovarro SA. ALL RIGHTS RESERVED.


Copyright in the whole and every part of this document belongs to Ovarro SA (‘the Owner’) and may not be used,
sold, transferred, copied or reproduced in whole or in part in any manner or form or in or on any media to any
person other than in accordance with the terms of the Owner’s agreement or otherwise without the prior written
consent of the Owner.

Version: 2.20 Page 129 of 129

You might also like