Professional Documents
Culture Documents
for
A
User’s Guide
Version 2.17
Disclaimer
Every effort has been made to ensure the accuracy of the information in this guide. However, Servelec-Technologies assumes no
responsibility for the accuracy of the information. Product information is subject to change without notice.
In case of question, you can send an e-mail to support.tbox@servelec-technologies.com
Copyright
2004-2016 by Drève Richelle, 161 - bâtiment M
1410 Waterloo - Belgium
3. TIMERS ......................................................................................................................... 97
Version: 2.17 BASIC & Ladder 5
Presentation ............................................................................................................. 97
Introduction.............................................................................................................. 98
Creating a Timer........................................................................................................ 98
The variables of a Timer ............................................................................................ 99
3.4.1. Saving Dynamic Preset ........................................................................................................................ 100
Using Timers in Ladder .............................................................................................100
3.5.1. The instance name .............................................................................................................................. 101
3.5.2. The Preset ........................................................................................................................................... 101
Using Timers in BASIC ..............................................................................................102
3.6.1. Reminder ............................................................................................................................................ 102
3.6.2. Syntax.................................................................................................................................................. 102
3.6.3. Reset Timer Function .......................................................................................................................... 103
3.6.4. Examples ............................................................................................................................................. 103
Using Timers in POUs ...............................................................................................103
Timer – Single Shot ..................................................................................................104
Timer – Monostable .................................................................................................105
Timer – Integral .......................................................................................................106
Timer – On Delay .....................................................................................................108
4. COUNTERS ..................................................................................................................109
Presentation ............................................................................................................109
Introduction.............................................................................................................110
Creating a Counter ...................................................................................................110
The variables of a Counter........................................................................................111
Using Counters in Ladder .........................................................................................112
4.5.1. The contact used with the pulse input ............................................................................................... 112
4.5.2. The instance name .............................................................................................................................. 112
4.5.3. The Preset ........................................................................................................................................... 113
Using Counters in BASIC ...........................................................................................114
4.6.1. Reminder ............................................................................................................................................ 114
4.6.2. Syntax.................................................................................................................................................. 114
4.6.3. Reset Counter Function ...................................................................................................................... 114
Using Counters in POUs ............................................................................................114
Counter - UP ............................................................................................................115
Counter - DOWN ......................................................................................................116
Counter - RING .........................................................................................................118
5. LIBRARY MANAGER .....................................................................................................120
Import of POUs (saving POUs in a Library) ................................................................120
Export of POUs (retrieval of POUs from a library) .....................................................121
Use of a Library in a TWinSoft document ..................................................................121
INDEX ................................................................................................................................122
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
1.2.1. Case
BASIC is not case sensitive.
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)
1.2.4. 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 chapter 1.18)
Variable : a variable appear in black color
The cycle time is available from the ‘RTU Identification’, accessible in the main menu
'Communication'.
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.
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
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 In an arithmetic operation, a constant is always
hexadecimal: a=&H1E240 converted into the format of the Tag it is associated to.
Floating point: a=123.456 Integer/2.5
Constant will be converted to Integer, it means 2
See also chapter 1.9.
[x] is the index of the variable in the table. Only square brackets [ ] can be used.
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
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
Each variable of the table can be represented with the name of the table and its index:
Table[1]
Table[2]
....
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)
= : 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
Arguments
result :Bool
expression :any expression composed of Bool, Byte, Word, Long, Float
Examples
Status=Value<>0
if (level<=125) then
Pump=1
endif
Syntax
Classical syntax: with Statements on different lines:
If Condition1 then
Statement1
Statement2
elseif Condition2 then In this example:
Statement3 If Condition1 is TRUE, Statement 1 and 2 are
else executed.
Statement4
endif
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
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)
Example:
INT * LONG calculated in LONG
Examples:
RESULT=WORD * 10.9 if WORD=100, RESULT=1100 (you can force the casting of
the constant. See chapter 1.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
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
Syntax
result=expression1+expression2+ expression3 ...
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
1.9.5. - (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
Syntax
result=expression1*expression2*expression3 ...
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
1.9.7. / (Division)
Divides numbers.
Syntax
result=expression1/expression2/expression3 ...
Arguments
result :Byte, Word, Long, Float
expression :any expression composed of Bool, Byte, Word, Long, Float
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
Syntax
result=number1 % number2
Arguments
result :Word, Long, Float
numbers :Word, Long
Examples
Remainder=47 % 15 'Remainder=2
1.10.1. 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)
1.10.2. 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
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
1.10.4. 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
Notes:
1. The NOT function is a complement to 1
2. An inversion (a=-b) is a (complement to 1) + 1
Examples:
Syntax
result=Not expression
Arguments
result :Word or Long
expression :any expression composed of Bool, Byte, Word, Long
Examples
MyVal=Not Word1
It is the ideal tool to execute repetitive procedure. Be careful using big value for i.
With function For…Next, the program
Syntax jumps out of the routine when all steps
For ... next i have been executed.
Statements are executed n times: If there are too many, the program might
Dim i as Word
For i=x to n step y generate a watchdog.
Statement You should then use For … nextcycle
Statement
next i
Example
For...Next statements nested
Syntax
Classical syntax
While condition
statement1
statement2
Wend
Argument
condition : Bool, Tag or expression
Example
While level>150
call Alarms
Wend
1.13.1. Trigonometric
The trigonometric functions supported are:
Sine, Arcsine, Cosine, Arccosine, Tangent, Arctangent.
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
Syntax
Result=Log(x)
Result=Ln(x)
Argument
x : Single or constant
result : Single
1.13.3. 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
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
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
Syntax
inc(Var)
Argument
Var :must be any Integer variable: Byte, Word, Long
Example
If TriggerPos(Pump_0) then
inc(Counter_0)
endif
1.14.2. 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
1.14.3. ABS
The ABS function returns the absolute value of any variable.
Syntax
Result=abs(Var)
Argument
Var :any format: Byte, Word, Long, Float
Syntax
Result=LoByte(Var)
Argument
Var :Word (16 bits)
Result :Byte or Word
1.14.5. 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
1.14.6. 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
Syntax
Result=HiWord(Var)
Argument
Var :DWord (32 bits)
Result :Word
Example
HighestWord=HiWord(Long)
1.14.8. 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
1.14.9. 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
Use the same format of Tag for Var
Var :Word or DWord and Result
Shift :Word or Constant
Result :Word or Dword
Syntax
Result=SHR(Var,shift)
1.14.11. 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
1.14.12. 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))
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
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)
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
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
1.14.16. 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
1.14.17. 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
IMPORTANT:
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:
Becomes:
If TriggerPos (PrgRun!) then Flag=MyTag
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
1.14.19. 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
Syntax
Long_register=Truncate(Single_register)
Argument
Long_register : Long
Single_register : Single
Examples
Whole_value = Truncate(Floating_reg)
1.14.21. 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)
1.14.22. 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)
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.
You then use the function appropriate to the format of the Tag as follows:
Average=sampleword(1,0)
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
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
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.
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
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)
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 doted IP address in T (string or Text Tag) into a DWord (n)
T=StrToIP(n) converts the DWORD (n) into a doted IP address in a Text Tag (T)
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.
Arguments
Pointer : Word register containing the ModBus address of the variables.
Digital : Boolean variable to receive the status at the address of 'Pointer'.
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'
Syntax
Pointer=AdrOf(Tag)
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).
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 chapter 1.18) or Tag names.
Syntax
Goto Label
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
CountDown Samplebyte
CountUp Sampleword
CountRing Sampledword
CountReset Samplesingle
CSng SetBit
CStr Shl
CWord Shr
Sine
Dec Single
Dim SplitBit
DWord Sqrt
Step
Else StrToAscii
Elseif StrToIp
Endif SwapByte
Exp
Tablesize
For Tan
Then
GetRTUTime TimerSS
GetRTUDate TimerMS
Goto TimerIN
TimerOD
HiByte TimerReset
HiWord To
Integer TriggerNeg
TriggerPos
If Truncate
Inc
InStr Xor
IpToStr
UCase
LCase
Len Wend
Left While
Let Word
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).
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.
Double click 'Add a POU', type a Name (No accent, space or keywords (see chapter 1.18)) and
check the type 'Program'.
Click OK.
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.
Syntax
To call a Program, use the syntax:
call Alarms 'Alarms is the name of the POU Program
Double click 'Add a POU', type a Name (No accent, space or keywords (see chapter 1.18)) and
check the type 'Function'.
Select the type of the output (result of the calculation): BOOL, WORD, LONG or FLOAT.
Click OK.
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.
To check the Tags, look in the ‘list of Tags’ to the global Tags
associated to the arguments.
Syntax
Result=Function(Arg1, Arg2, Arg3, ...)
Arguments
Result the Tag receiving the result of the Function
Function the name of the 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)
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.
Double click 'Add a POU', type a Name (No accent, space or keywords (see chapter 1.18)) and
check 'Function Block'.
Click OK.
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.
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 ouput.
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.
is a digital output. It will be connected to a motor, for instance when
OUTPUT
calling the Function Block.
The programming
You use BASIC language for programming.
Example of Instantiation:
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)
To see an example, load the TWinSoft document 'MSLadder.tws' that you find in the 'Samples'
directory of TWinSoft.
2.2.1. 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.
2.2.2. 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 chapter 1: BASIC)
The selection of different types of Output is accessible in the LD Toolbar.
Example of Ladder
Ladder - Modes
2.3.1. 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.
The Ladder diagram is drawn in red lines with the Tags associated at each input contact, output
relay or IN/OUT of functions.
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.
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.
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 chapter 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
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')
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 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 can be used in any POU Program and Function Block (see next).
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.
You type its name and press <ENTER> to create it. The Tag can be either
The Tag does not exist
Local Tag or Global Tag (see previous chapter ‘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.
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 use the following Tags (see the corresponding TBOX manual chapter: 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.
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.
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.
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.
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.
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.
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.
You might find difficulties in drawing line, then it is important you understand the rules:
That’s it !
- 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 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
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
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
'anaOUT' is the result of the logical AND between 'ana0' and 'ana1'
Example: 0001000011111111
AND 0001100000001111
0001000000001111
'anaOUT' is the result of the logical XOR between 'ana0' and 'ana1'
Example: 0000000011111111
XOR 1111000000001111
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
'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).
To insert a Math block, in the edit mode of Ladder Programming, click the icon of the LD
Toolbar.
2.10.1. 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:
An assignment operation is always executed from the right to the left. In other words, we have:
result = operation
or: 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.
2.10.3. 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
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.17 BASIC & Ladder 78
2.10.5. 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 (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 = 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.
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)
2.10.9. 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.
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 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).
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...)
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’ 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.
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.
- 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.
2.13.1. 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.
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.
Double click 'Add a POU', type a Name (No accent, space or keywords (see BASIC)) and check
'Function'.
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.
3.
Now you can create Ladder Diagram for the Function you have defined.
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.
- 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.
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.
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.
Now you create Ladder Diagram for the Function Block you have defined.
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
OUTPUT
calling the Function Block.
is an analog input containing the number of seconds of the delay. It must
DELAY
be associated 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.17 BASIC & Ladder 94
2.14.4. 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.
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.
Presentation
Timers are used for counting a time, a delay.
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.
The way of using timer in Ladder is discussed in chapter 3.5 and in BASIC chapter 3.6.
Each model is presented with a diagram in chapters 3.8, 3.9, 3.10 and 3.11
For each timer (regardless of type), there are two analog variables and one digital variable
associated with it:
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.
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.
When Tags are available, the current values appear in the list of Timers:
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
Once you have selected the type of timer, it appears in the Ladder line.
Example: Fan1
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 chapter 3.4. above).
You still have to indicate a constant here, it will not be used but is mandatory when calling the
function.
If you want to clear a timer, you select the Function 'ResetTimer' associated to its name.
3.6.1. 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
3.6.2. 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 chapter 3.3. above)
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 chapter 3.3. and 3.4.
above)
Syntax
TimerReset (Name)
Argument
Name : It is the name of the timer you have created (see chapter 3.3. above)
3.6.4. 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)
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)
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)
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
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
The re-activation of the Tag INPUT allows the timer continuing and completes the cycle.
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.
Presentation
Counters are used for counting pulses
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.
The way of using counter in Ladder is discussed chapter 4.5 and in BASIC chapter 4.6.
Each model is presented with a diagram in chapters 4.8, 4.9 and 4.10
For each counter (regardless of type), there are two analog variables and one digital variable
associated with it:
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.
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.
When Tags are available, the current values appear in the list of Counters:
Once you have selected the type of counter, it appears in the Ladder line.
Example: Pump1_Hours
If you want to clear a counter, you select the Function 'ResetCount' associated to its name.
4.6.1. Reminder
Three types of counters are available:
4.6.2. 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 chapter 4.3. above)
Start : INPUT Bool. The Tag or expression that increments the counter.
Syntax
CountReset (Name)
Arguments
Name : It is the name of the counter you have created (see chapter 4.3. above)
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)
Counter - UP
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.
Counter - DOWN
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.
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).
A library is a file with the extension .LIB, saved by default in the directory of TWinSoft.
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.
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’.
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.
BASIC (next)........................................................................ 7
suffix ............................................................................. 9
A Tags ............................................................................... 9
Address of (function) .................................................. 47, 82 Text Functions............................................................. 44
trigger ......................................................................... 38
trigonometry ............................................................... 27
B Truncate ...................................................................... 40
types of variable ......................................................... 12
BASIC .................................................................................. 7 while...wend ............................................................... 26
- (subtraction) .............................................................. 18 XOR ............................................................................. 22
* (multiplication) ......................................................... 19 Break line ........................................................................... 9
/ (division) ................................................................... 19
+ (addition) .................................................................. 18
abs ............................................................................... 31 C
AND ............................................................................. 21
assignment .................................................................. 11 Case .................................................................................... 8
BCD .............................................................................. 40 Colors
bit manipulation .......................................................... 34 BASIC ............................................................................. 8
break line....................................................................... 9 Ladder ......................................................................... 65
byte manipulation ....................................................... 32 Constant
case ............................................................................... 8 BASIC ....................................................................... 8, 10
colors ............................................................................. 8 in timer (BASIC) ......................................................... 102
comment ..................................................................... 10 in timer (Ladder) ....................................................... 101
comparison.................................................................. 13 type casting ................................................................. 17
constant ...................................................................... 10 Counters ......................................................................... 109
dec ............................................................................... 31 Down......................................................................... 116
Dim .............................................................................. 12 in BASIC ..................................................................... 114
exponential ................................................................. 28 in Ladder ................................................................... 112
for...next...step ............................................................ 24 in POU ....................................................................... 114
for...nextcycle .............................................................. 24 Ring ........................................................................... 118
functions ..................................................................... 30 Up 115
general .......................................................................... 8 variables .................................................................... 111
GetRtuDate ................................................................. 43 Cycle
GetRtuTime ................................................................. 43 sequence of tasks ......................................................... 7
Goto ............................................................................ 47 Cycle time................................................................9, 10, 61
if...then...else…elseif ................................................... 14
inc 31 G
indirect addressing ...................................................... 46
keywords ................................................................. 8, 48 Goto ................................................................................. 47
label ............................................................................. 47
line feed ........................................................................ 8
logarithms ................................................................... 28
I
ModBus address function ........................................... 47 Indirect Addressing .......................................................... 46
modulo ........................................................................ 20 in BASIC ....................................................................... 46
NOT ............................................................................. 23 Ladder ......................................................................... 81
Odd .............................................................................. 40
OR 22
Pack32 ......................................................................... 37 K
PackBit......................................................................... 35
Peek ............................................................................. 46 Keywords...................................................................... 8, 48
Poke............................................................................. 46
POU ............................................................................. 49
power .......................................................................... 29
precautions ................................................................. 10
putchrono .................................................................... 39
sampling tables ........................................................... 41
SetBit ........................................................................... 34
shift ............................................................................. 33
Split32 ......................................................................... 37
SplitBits ....................................................................... 36
square root .................................................................. 29
W
P
Watchdog ...........................................................................9
Peek .................................................................................. 46