IEC 61131-3 Programming (LogicLab) PDF
IEC 61131-3 Programming (LogicLab) PDF
INDEX
1 - LogicLab.................................................................................................................................................................... 7
2 - System resources...................................................................................................................................................... 8
2.1 - Memory structure................................................................................................................................................. 9
2.2 - Backup memory (Retain)................................................................................................................................... 10
2.3 - Memory access.................................................................................................................................................. 11
3 - Data types definition................................................................................................................................................ 12
3.1 - FILEP, file pointer............................................................................................................................................... 12
3.2 - SYSSERIALMODE, serial port communication mode.......................................................................................12
3.3 - SYSCANMESSAGE, CAN message................................................................................................................. 12
4 - System variables..................................................................................................................................................... 13
4.1 - Read only variables (System variables)............................................................................................................. 14
4.2 - Read and write variables (System variables)..................................................................................................... 16
4.3 - Product unique ID.............................................................................................................................................. 17
5 - Data definition.......................................................................................................................................................... 18
5.1 - Variable types definition..................................................................................................................................... 18
5.2 - Task ID definition................................................................................................................................................ 18
5.3 - TermIO, definitions for terminal I/O.................................................................................................................... 19
5.4 - FSeek origin definition....................................................................................................................................... 19
5.5 - Serial mode definition........................................................................................................................................ 19
5.6 - CAN bit rate definition........................................................................................................................................ 19
5.7 - Digital input mode.............................................................................................................................................. 20
5.8 - Digital output mode............................................................................................................................................ 20
5.9 - Analog to digital mode........................................................................................................................................ 21
5.10 - Digital to analog mode..................................................................................................................................... 22
5.11 - Spy mode, spy mode definition........................................................................................................................ 22
6 - Functions defined by LogicLab................................................................................................................................ 23
6.1 - Mathematical and trigonometric functions.......................................................................................................... 24
6.2 - String functions.................................................................................................................................................. 26
7 - Functions and FBs................................................................................................................................................... 27
- Functions................................................................................................................................................................ 27
- Function Blocks...................................................................................................................................................... 27
7.0.1 - Functions and embedded FBs................................................................................................................... 27
7.0.2 - Libraries..................................................................................................................................................... 28
7.0.3 - Import library.............................................................................................................................................. 28
7.0.4 - Import a library........................................................................................................................................... 29
7.0.5 - Import library objects................................................................................................................................. 30
7.0.6 - Considerations about links to library and import of objects........................................................................31
7.0.7 - Functions and function blocks protection................................................................................................... 32
7.1 - Functions and FBs for Flip/Flop management................................................................................................... 33
7.1.1 - F_TRIG, Falling edge trigger..................................................................................................................... 33
1 LogicLab
LogicLab is a IEC61131-3 PLC compiler that supports all 5 programming languages of the standard, Easy-to-use textual
and graphic editors, extended drag & drop functions applying to all contexts of the framework, various integrated textual
and graphic debuggers make LogicLab an efficient development environment and a particularly user-friendly program
The LogicLab's compiler generates directly the machine code for the target processor, guaranteeing high speed
execution time. The tool has been developed by Axel, an Italian Company with multiyear experience in industrial
automation software production, and customized to be used with the our programmable controllers.
2 System resources
The logic I/O are automatically handled by the operating system in the process image. The operating system transfers
to the state of all logic inputs in the input image in system memory and transfers the value in the output image from
memory system to the logic outputs.
So testing the state of the memory image of the logic inputs, will be checked the status of the logic inputs. (Example
IX0.0 corresponds to the input 0 of module extension 0; IX1.5 corresponds to the input 5 of the module extension 1).
Writing the image memory of the logic outputs, will be set the status of the logic output (Example QX0.0 is of the output
0 od extension module 0; QX1.5 is the logic output 5 of extension module 1).
The logic I/O can be managed through the functions SysGetPhrDI and SysSetPhrDO.
The analog I/O can be managed by SysGetAnInp and SysSetAnOut functions.
The counters can be managed by the function block SysGetCounter
The encoder inputs can be managed by the function block SysGetEncoder.
The CAN bus is managed by the function block SysCANRxMsg e SysCANTxMsg.
To access to serial ports on the CPU module, the Sysfopen function must used defining the name of the port to use.
There are extension modules that are equipped with serial ports, the access to these ports is exactly the same as the
ports on the CPU module. Using the definition PCOMx.y with x indicates the module address and y is the port number
on the module. (Example PCOM0.0 0 defines the port 0 on the module 0; PCOM1.2 indicates the port 2 on module 1
and so on).
To access the file system (Both on the internal disk od on the SD Card), you must use the Sysfopen.
In models with an Ethernet port, you can manage UDP and TCP/IP connections by using the Sysfopen.
DB Dimensione Descrizione
IX0 32 Bytes Logic input module 00 (R)
IX1 32 Bytes Logic input module 01 (R)
IX2 32 Bytes Logic input module 02 (R)
IX3 32 Bytes Logic input module 03 (R)
IX4 32 Bytes Logic input module 04 (R)
IX5 32 Bytes Logic input module 05 (R)
IX6 32 Bytes Logic input module 06 (R)
IX7 32 Bytes Logic input module 07 (R)
IX8 32 Bytes Logic input module 08 (R)
IX9 32 Bytes Logic input module 09 (R)
IX10 32 Bytes Logic input module 10 (R)
IX11 32 Bytes Logic input module 11 (R)
IX12 32 Bytes Logic input module 12 (R)
IX13 32 Bytes Logic input module 13 (R)
IX14 32 Bytes Logic input module 14 (R)
IX15 32 Bytes Logic input module 15 (R)
IX255 32 Bytes Logic input CPU module (R)
QX0 32 Bytes Logic output module 00 (R/W)
QX1 32 Bytes Logic output module 01 (R/W)
QX2 32 Bytes Logic output module 02 (R/W)
QX3 32 Bytes Logic output module 03 (R/W)
QX4 32 Bytes Logic output module 04 (R/W)
QX5 32 Bytes Logic output module 05 (R/W)
QX6 32 Bytes Logic output module 06 (R/W)
QX7 32 Bytes Logic output module 07 (R/W)
QX8 32 Bytes Logic output module 08 (R/W)
QX9 32 Bytes Logic output module 09 (R/W)
QX10 32 Bytes Logic output module 10 (R/W)
QX11 32 Bytes Logic output module 11 (R/W)
QX12 32 Bytes Logic output module 12 (R/W)
QX13 32 Bytes Logic output module 13 (R/W)
QX14 32 Bytes Logic output module 14 (R/W)
QX15 32 Bytes Logic output module 15 (R/W)
QX255 32 Bytes Logic output CPU module (R/W)
MX0 512 Bytes Read-only system variables (R)
MX1 512 Bytes Read/Write system variables (R/W)
MX100 4096 Bytes User Memory (R/W). From address 2048 to 4095 the data are retentive.
As you can see from the picture, the Var2 variable is declared with the RETAIN attribute and will maintain its value even
during system power off. The Var5 variable allocated in the user memory MD100.2048 although does not require the
RETAIN attribute, is retained because allocated in the retain range.
In the project window, all global variables are grouped according to their definition.
One folder is for retentive variables. As you can see, only Var2 is present. Var5 is not
present although retentive too, because it is allocated in the user memory.
MB100.0 MB100.0
LSB MSB
LSB MSB
Warning! SlimLine is based on ARM architecture, and this type of architecture assumes that:
The 16-bit variables (WORD, INT, UINT) are allocated at memory addresses divisible by 2. So this type of variable can
be allocated for example at MW100.32 but not at address MW100.33.
The 32-bit variables (DWORD, DINT, UDINT, REAL) are allocated at memory addresses divisible by 4. So this type of
variable can be allocated for example at MD100.32 but not at address MD100.33, MD100.34, MD100.35.
This rule is automatically applied by the LogicLab compiler also regarding the data structures, on a definition of a data
structure composed of heterogeneous variables LogicLab automatically inserts padding bytes to properly align 16 bits
and 32 bits variables.
4 System variables
With the LogicLab development environment are published system variables that can be referenced in the program to
access system information. The variables are displayed in the LogicLab library window.
If the window is not displayed, you must enable the display by the menu item Wiew → Tool windows → Library.
Activating the Tab Target variables will see a list of all published variables divided into folders. A double-click on the
System variables folder opens the folder displaying all published variables (See picture at right).
5 Data definition
In addition to the folders of the system variables, there are also folders with identifiers of type information needed to
identify a given system data.
PCB099
PCB122
PCB126
Define Type Value Description
PCB099
PCB122
PCB126
Define Type Value Description
LD example
IL example
LD Minuend
SUB Subtrahend
ST Result
ST example
Result:=SUB(Minuend, Subtrahend); (* Subtraction using SUBB *)
Result:Minuend-Subtrahend; (* Subtraction as before *)
LN ANY_REAL LN(ANY_REAL)
It calculates the natural logarithm (Base "e" 2.71828) of a number.
Result:=LN(10.0); (* Result is 2.30259 *)
Functions
The functions have a variable number of input data and one only data output. To use them, just put them in the LD and
FBD programs and connect them to the variables. In the IL programs, they must be called with the statement CAL. In
the ST programs simply indicate the name to be executed.
Function Blocks
The FBs unlike functions, allocate a variable in the program that contains all the variables of input and output handled
by the function block. To use them just put them in the LD and FBD programs and connect them to the variables. In the
IL programs they must be called with the statement CAL. In the ST programs simply indicate the name to be executed.
7.0.2 Libraries
In addition to the functions and embedded FBs, some libraries are provided. They contain a variety of functions and
function blocks that can be used in your program. The libraries are provided with LogicLab in the installation directory
ProgramFiles\Elsist\IEC61131Suite\LogicLab2p0\Libraries, but you can also use libraries provided subsequently or
which have been downloaded from the site. There are two ways to use the libraries:
Import library: In this way, all the items in the library are imported into your program and the objects can thus be used
in the program. This is a good solution. The drawback is to increase the size of the LogicLab project file (*.ppjs), as well
as its own program must contain all the objects of the imported library. The executable generated will contain only
the used objects, however.
Import objects: In this way you can import only the objects from a library (functions, FBs, etc.) that affect, which will
become an integral part of their project.
Acting on the Add button, opens a browser window of the disk. Choose the directory where is placed the library, and
select the file to be imported.
Acting on the Close button, in the LogicLab Library
window (Ctrl-L) will show an additional tab, one for
each imported library.
Simply drag the desired object in your project to use
it.
ST example
(* Check the protection codes. *)
(* [End of file] *)
Normally the protected functions and function blocks can operate in demo mode for a certain period of time on their first
run after the system power on. After the test period, the operation ends, and they generates an error that is detectable
by the function SysGetLastError.
This function block enables the Q output for a program loop on the falling edge of the CLK clock.
CLK (BOOL) Clock. On the falling edge signal, the Q output is turned on for a program loop.
Q (BOOL) Output. Active for a program loop on the falling edge of the CLK clock input.
Examples
On the falling edge of the digital Di00M00, digital output Do00M00 became enabled for a program loop.
Defining variables
IL example
CAL FBF_TRIG (* Call the F_TRIG function block *)
LD Di00M00
ST FBF_TRIG.CLK (* Transfer the digital input to the function block clock *)
LD FBF_TRIG.Q
ST Do00M00 (* On the falling edge of digital input the output is set *)
ST example
FBF_TRIG(); (* Call the F_TRIG function block *)
Type Library
7.1.2 R_TRIG, Raising edge trigger
FB ePLCStdLib_B000
This function block enables the Q output for a program loop on the rising edge of the CLK clock.
CLK (BOOL) Clock. On the rising edge signal, the Q output is turned on for a program loop.
Q (BOOL) Output. Active for a program loop on the rising edge of the CLK clock input.
Examples
On the rising edge of the digital Di00M00, digital output Do00M00 became enabled for a program loop.
Defining variables
IL example
CAL FBR_TRIG (* Call the R_TRIG function block *)
LD Di00M00
ST FBR_TRIG.CLK (* Transfer the digital input to the function block clock *)
LD FBR_TRIG.Q
ST Do00M00 (* On the raising edge of digital input the output is set *)
ST example
FBR_TRIG(); (* Call the R_TRIG function block *)
Type Library
7.1.3 RS, Reset/Set flip flop
FB ePLCStdLib_B000
This function block, on activation of the S command, set the Q1 output that remains active even when the
command is deactivated. To deactivate the output, the R1 reset must be activated.
The R1 reset command has priority on S set command.
S (BOOL) Set. On activation of the signal, the Q1 output is activated and remains active even when the command is
deactivated.
R1 (BOOL) Reset. On activation of the signal, the Q1 output is deactivated. Reset has priority on Set.
Q1 (BOOL) Output. Activated or deactivated according to the S set command and R1 reset command.
Examples
On activation of the Di00M00 digital input, the Do00M00 digital output becames active even when the digital input is
deactivated. To deactivate the digital output, you must activate the Di01M00 digital input.
Note! The Di01M00 digital input has priority on Di00M00.
Defining variables
IL example
CAL FBRS (* Call the RSG function block *)
LD Di00M00
ST FBRS.S (* Transfer the digital input to the set command *)
LD Di01M00
ST FBRS.R1 (* Transfer the digital input to the reset command *)
LD FBRS.Q1
ST Do00M00 (* The function block output is copied to digital output *)
ST example
FBRS(); (* Call the RS function block *)
Type Library
7.1.4 SR, Set/Reset flip flop
FB ePLCStdLib_B000
This function block, on activation of the S1 command, set the Q1 output that remains active even when the
command is deactivated. To deactivate the output, the R reset must be activated.
The S1 set command has priority on R reset command.
S1 (BOOL) Set. On activation of the signal, the Q1 output is activated and remains active even when the command is
deactivated. Set has priority on Reset.
R (BOOL) Reset. On activation of the signal, the Q1 output is deactivated.
Q1 (BOOL) Output. Activated or deactivated according to the S set command and R1 reset command.
Examples
On activation of the Di00M00 digital input, the Do00M00 digital output becames active and remains active even when
the digital input is deactivated. To deactivate the digital output you must activate the Di01M00 digital input.
Note! The Di00M00 digital input has priority on Di01M00.
Defining variables
IL example
CAL FBSR (* Call the SR function block *)
LD Di00M00
ST FBRS.S1 (* Transfer the digital input to the set command *)
LD Di01M00
ST FBRS.R (* Transfer the digital input to the reset command *)
LD FBRS.Q1
ST Do00M00 (* The function block output is copied to digital output *)
ST example
FBSR(); (* Call the SR function block *)
This function block performs the timing on deactivation. Activating the IN input, the Q output is activated
immediately and the time on ET output is reset. Deactivating the IN input, starts the count and after the
time set PT expressed in mS, you disable the Q output. On ET output, is back out the time elapsed since
the deactivation expressed in mS.
IN (BOOL) Timer input. Activated, the Q output is activated immediately and the ET time output is reset. Deactivated,
the count starts and after the time set in PT, the Q output is deactivates.
PT (UDINT) Preset time. Defines the delay time from input IN deactivation and Q output deactivation, expressed in mS.
Q (BOOL) Timer output. It is activated on IN input activation, and it is deactivated after the time set by PT from IN
input deactivation.
ET (UDINT) Timer time. It is reset on IN input activation and it starts counting from the IN input deactivation. Reached
the set time in PT, it stops counting. It is expressed in mS.
Examples
The timer is preset to 1 second (1000 mS). Activating the Di00M00 digital input, the Do00M00 digital output is activated
immediately and the time value in the VarOut variable is clear.The timer is preset to 1 second (1000 mS).
Deactivating the Di00M00 digital input, the timer starts counting and the value of elapsed time is copied in the VarOut
variable. After the interval, the Do00M00 digital output is disabled.
Defining variables
IL example
CAL FBeTOF (* Call the eTOF function block *)
LD Di00M00
ST FBeTOF.IN (* Transfer the digital input to timer input *)
LD 1000
ST FBeTOF.PT (* Set the delay time *)
LD FBeTOF.Q
ST Do00M00 (* When time is passed the digital output is set *)
LD FBeTOF.ET
ST OutValue (* The counting time is copied to variable *)
Type Library
7.2.2 eTON, Timer On
FB ePLCStdLib_B000
This function block performs the timing on the activation. By activating the IN input, the count starts and
after the time set in PT expressed in mS, activates the Q output. On ET is back out the elapsed time since
input activation expressed in mS. Turning off the IN input, the Q output deactivates instantaneously and the
time value in ET is reset.
IN (BOOL) Timer input. Activating it, the count start and after the time set in PT, the Q output is activated. Disabling it,
the Q output is deactivated immediately and the ET output value is reset.
PT (UDINT) Preset time. Defines the time delay from IN input activation to Q output activation, expressed in mS.
Q (BOOL) Timer output. It is activated after the time set in PT from the IN input activation and deactivated when IN
becames deactivated.
ET (UDINT) Timer time. Start counting from the IN input activation. Reached time set in PT, the counting stop. It is clear
on IN input deactivation.
Examples
On activation of the Di00M00 digital input, after 1 S (1000 ms) the Do00M00 digital output is activated. Deactivating the
Di00M00 digital input, the Do00M00 digital output is deactivated immediately.
Defining variables
IL example
CAL FBeTON (* Call the eTON function block *)
LD Di00M00
ST FBeTON.IN (* Transfer the digital input to timer input *)
LD 1000
ST FBeTON.PT (* Set the delay time *)
LD FBeTON.Q
ST Do00M00 (* When time is passed the digital output is set *)
LD FBeTON.ET
ST OutValue (* The counting time is copied to variable *)
ST example
FBeTON(PT:=1000); (* Call the eTON function block *)
Type Library
7.2.3 eTP, Timer pulse
FB ePLCStdLib_B000
This function block performs the timing of trigger pulse. Activating the IN input, the Q output becomes active
and in ET there is the elapsed time (in ms) from impulse activation. Reached the PT set time (in ms),
regardless of the status of IN, the Q output is reset, while the time on ET is reset only if IN input becomes
deactive.
IN (BOOL) Timer input. Activating it, the Q output is activated and the count begins. After the time set in PT regardless
of the status of IN input, the Q output becomes deactive.
PT (UDINT) Preset time. Defines the activation time of Q output, expressed in mS.
Q (BOOL) Timer output. It is activated on IN input activation for the time defined in PT.
ET (UDINT) Timer time. Start counting from the activation of IN input. Reached the PT set time, it stops counting. It is
expressed in mS.
Examples
The timer is preset to 5 seconds (5000 mS). Activating the Di00M00 digital input, the Do00M00 digital output is
activated immediately and the time value in the VarOut variable starts counting. Reached the set time (5 seconds), the
Do00M00 output is deactivated while the value of time in the VarOut variable remains locked on the preset value (5000
ms) until the deactivation of Di00M00.
Deactivating the Di00M00 digital input during the timing count, did not affect either Do00M00 output status, nor the
value of the VarOut variable.
Defining variables
IL example
CAL FBeTP (* Call the eTP function block *)
LD Di00M00
ST FBeTP.IN (* Transfer the digital input to timer input *)
LD 5000
ST FBeTP.PT (* Set the delay time *)
LD FBeTP.Q
ST Do00M00 (* When time is passed the digital output is set *)
LD FBeTP.ET
ST OutValue (* The counting time is copied to variable *)
ST example
FBeTP(PT:=5000); (* Call the eTP function block *)
This function block performs the management of a counter down. Acting on LD load input is possible at
any time to transfer the PV preset value on the CV counter. Each rising edge of the CD input, the CV
counter value is decreased. When the value reaches 0, the Q output is activated and the counting stops.
Only by acting on the LD load input is possible to preset the counter and to restart the counter again.
The LD load input has priority over the CD decrease input.
CD (BOOL) Decrement counter command. For each rising edge, the CV counter value is decreased.
LD (BOOL) Load command. Activating the input the PV preset value is transferred to the CV counter value.
PV (INT) Preset value. Activating the LD load input, the value is transferred to the CV.
Q (BOOL) Counter output. Activated when the counter value reaches 0.
CV (INT) Counter value. When the value reaches 0, the output Q is set and the counter does not decrease any
more.
Examples
The counter is preset to 10 and its output value (CV) is copied in OutValue. Activating the Di01M00 digital input the
counter is preset and its CV output value is set at 10, also resetting the Q output.
On the Di00M00 rising edge, the digital counter is decremented by 1. When the count reaches zero, the count stops
and the Q output of the counter is activated so also the Do00M00 digital output. To restart the count must activate the
Di01M00 digital input that preset the counter.
Defining variables
IL example
CAL FB_CTD (* Call the CTD function block *)
LD 10
ST FB_CTD.PV (* Preset value *)
LD Di00M01
ST FB_CTD.CD (* On the raising edge of digital input the counter count down *)
LD Di01M00
ST FB_CTD.LD (* If the digital input is set the PV value is loaded *)
LD FB_CTD.Q
ST Do00M00 (* If the counter value is 0 the digital output is set *)
LD FB_CTD.CV
ST OutValue (* The counter value is copied to the variable *)
ST example
FB_CTD(PV:=10); (* Call the CTD function block and preset counter *)
FB_CTD.CD:=Di00M00; (* On the raising edge of digital input the counter count down *)
FB_CTD.LD:=Di01M00; (* If the digital input is set the PV value is loaded *)
Do00M00:=FB_CTD.Q; (* If the counter value is 0 the digital output is set *)
OutValue:=FB_CTD.CV; (* The counter value is copied to the variable *)
Type Library
7.3.2 CTU, Counter Up
FB ePLCStdLib_B000
This function block performs the operation of an incremental counter. Acting on R reset input, at any time
you can reset the CV counter value. Each rising edge of CU input, the counter value CV is incremented.
When the value of the counter CV reaches the preset value, defined on PV, output Q is activated and the
counting stops. Only with the R reset input the counter will be reset and you will be able to restart the
counter again.
The R reset input is priority on CU.
CU (BOOL) Increment counter command. For each rising edge, the counter value CV is increased.
R (BOOL) Reset command. Activating the input, the value of the counter is reset.
PV (INT) Preset value. When the value of the CV counter reaches this value, the Q output is set and the counter no
longer increments.
Q (BOOL) Counter output.Activated if the CV value of the counter reaches the value defined in PS.
CV (INT) Value counter. When it reaches the PV preset value, the Q output is set and the counter does not
increment anymore.
Examples
The counter is preset to 10 and its CV output value is copied in the OutValue variable. Activating the Di01M00 digital
input, the counter is reset and its CV output value is set to 0, also resetting the Q output.
On the Di00M00 rising edge, the counter is incremented by 1. When the count value reaches the preset value, the
count stops and the Q output of the counter is activated, so also the Do00M00 digital output is activated. To restart the
count must activate the Di01M00 digital input which resets the counter.
Defining variables
IL example
CAL FBCTU (* Call the CTU function block *)
LD 10
ST FBCTU.PV (* Preset counter *)
LD Di00M00
ST FB_CTU.CU (* On the raising edge of digital input the counter count up *)
LD Di01M00
ST FB_CTU.R (* If the digital input is set the counter is reset *)
LD FBCTU.Q
ST Do00M00 (* If the counter value has reached the preset the digital output is set *)
LD FB_CTU.CV
ST OutValue (* The counter value is copied to the variable *)
Type Library
7.3.3 CTUD, Counter Up/Down
FB ePLCStdLib_B000
This function block performs the operation of a counter up and down. Acting on R reset input, at any time
you can reset the CV counter value. Acting on LD input, is possible at any time to transfer the PV preset
value on the CV counter value.
Each rising edge of the CU input, the CV counter value is incremented. When the value of the CV counter
reaches the preset value, defined on PV, the Q output is set and the counting stops. Only with the R reset
input the counter will be reset and you will be able to restart the counter again.
Eachrising edge of the CD input, the CV counter value is decreased. When the value reaches 0, the Q
output is set and the counting stops. Only by acting on the LD input is possible to preset the counter and to
restart the counter again.
CU (BOOL) Increment counter command. For each rising edge of the counter, the CV value is increased.
CD (BOOL) Decrement counter command. For each rising edge, the counter value of CV decreases.
R (BOOL) Reset command. Activating the input, the value of the counter is reset.
LD (BOOL) Load command. Activating the input, the PV preset value is transferred to the CV counter value.
PV (INT) Preset value. When the value of the CV counter reaches this value, the Q output is set and the counter no
longer increments.
QU (BOOL) Output up counter. Activated if the value of the CV counter reaches the value defined in PS presets.
QD (BOOL) Down counter output. Activated if the value of CV counter reaches 0.
CV (INT) Counter value. When it reaches the PV preset value, the Q output is activated and the counter does not
increment anymore.
Examples
The counter is preset to 10 and its CV output value is copied in the VarOut variable. Activating the Di02M00 digital
input, the counter is reset and its CV output value is set to 0, also resetting the QU output. Activating the Di03M00
digital input the counter is preset and its CV output value is set at 10, also resetting the QD output.
On the rising edge of the Di00M00 digital input, the counter is incremented by 1. When the count value reaches the
preset value, the count stops and the QU output is activated, so also Do00M00 digital output. To restart the count must
activate the Di02M00 digital input which resets the counter.
On the rising edge of the Di01M00 digital input, the counter is decremented by 1. When the count reaches zero, the
count stops and activates the QD output that activates the Do01M00 digital output also. To restart the count must
activate the Di03M00 digital input that preset the counter.
Defining variables
IL example
CAL FB_CTUD (* Call the CTUD function block *)
LD 10
ST FB_CTUD.PV (* Preset value *)
LD Di00M00
ST FB_CTUD.CU (* On the raising edge of digital input the counter count up *)
LD Di01M00
ST FB_CTUD.CD (* On the raising edge of digital input the counter count down *)
LD Di02M00
ST FB_CTUD.R (* If the digital input is set the counter is reset *)
LD Di03M00
ST FB_CTUD.LD (* If the digital input is set the PV value is loaded *)
LD FB_CTUD.QU
ST Do00M00 (* If the counter value has reached the preset the digital output is set *)
LD FB_CTUD.QD
ST Do01M00 (* If the counter value is 0 the digital output is set *)
LD FB_CTUD.CV
ST OutValue (* The counter value is copied to the variable *)
ST example
FB_CTUD(PV:=10); (* Call the CTD function block and preset counter *)
Function paramters:
Variable (UDINT) Variable in which to test the bit.
Bit (USINT) Number of bit to test (Range from 0 to 31).
Return value:
(BOOL)
Selected bit status.
Examples
The state of bit 4 of the VarInp variable is transferred to Do00M00 digital output.
Defining variables
LD example
IL example
LD VarInp (* Variable input *)
VBitTest 4 (* Variable bit test *)
ST Do00M00 (* Transfer bit status to digital output *)
ST example
Do00M00:=VBitTest(VarInp, 4); (* Variable bit test *)
Type Library
7.4.2 VBitSet, Variable bit set
Function eLLabUtyLib_C030
Function paramters:
Value (BOOL) Bit value to set.
Variable (UDINT) Variable in which to set the bit.
Bit (USINT) Number of bit to set (Range from 0 to 31).
Return value:
(UDINT)
Variabile value after set of bit.
Examples
The state of Di00M00 digital input is transferred in bit number 8 of the VarOut variable.
Defining variables
LD example
IL example
LD Di00M00 (* Variable input *)
VBitSet VarOut, 8 (* Variable bit set *)
ST VarOut (* Transfer result to variable *)
ST example
VarOut:=VBitSet(Di00M00, VarOut, 8); (* Variable bit set *)
Type Library
7.4.3 BitToByte, Bit to byte conversion
FB eLLabUtyLib_C030
This function block allows you to convert 8 BOOL variables in a BYTE variable.
Examples
The 8 digital input of module 0 are transferred into the VarOut variable. Activating the Di00M00 digital input, the VarOut
variable value will be 1. Activating the Di01M00 digital input VarOut will be 2, and so on until activating the Di07M00
where VarOut assumes the value 128. Activating multiple inputs simultaneously, the VarOut variable will take the sum
of activated inputs.
For simplicity in the IL and ST examples are not reported all the bits.
Defining variables
LD Di07M00
ST FBData.b7 (* Transfer digital input to input bit *)
LD FBData.Out
ST VarOut (* Transfer the result to variable *)
Type Library
7.4.4 ByteToBit, Byte to bit conversion
FB eLLabUtyLib_C030
This function block allows you to convert a BYTE variable in 8 BOOL variables.
Examples
The state of bit 0 of the VarInp variable is transferred to Do00M0 digital output. The state of bit 1 of the VarInp variable
is transferred to Do01M00 digital output and so on until the status of bit 7 that is transferred to Do07M00 digital output.
For simplicity in the IL and ST examples are not reported all the bits.
Defining variables
LD FBData.b0
ST Di00M00 (* Transfer output bit to digital output *)
Type Library
7.4.5 ByteToWord, Byte to word conversion
FB eLLabUtyLib_C030
This function block allows you to convert two BYTE variables in a single WORD variable.
Examples
The MSBByte and LSBByte variables are joined in the VarOut output variable.
Defining variables
LD LSBByte
ST FBData.LSB (* Transfer the LSB variable to input *)
LD FBData.Out
ST VarOut (* Transfer output to variable *)
Type Library
7.4.6 WordToByte, Word to byte conversion
FB eLLabUtyLib_C030
This function block allows you to split a WORD variable into two BYTE variables.
Examples
The VarInp variable is splitted into two variables: MSBByte and LSBByte.
Defining variables
LD FBData.MSB
ST MSBByte (* Transfer the MSB output to variable *)
LD FBData.LSB
ST LSBByte (* Transfer the LSB output to variable *)
Type Library
7.4.7 DoubleToWord, Double to word conversion
FB eLLabUtyLib_C030
This function block allows you to split a DWORD variable into two WORD variables.
Examples
The VarInp variable is splitted into two variables: MSBWord and LSBWord.
Defining variables
LD FBData.MSW
ST MSBWord (* Transfer the MSW output to variable *)
LD FBData.LSW
ST LSBWord (* Transfer the LSW output to variable *)
Type Library
7.4.8 WordToDouble, Word to double conversion
FB eLLabUtyLib_C030
This function block allows you to join two WORD variables in a single DWORD variable.
Examples
The two variables MSBWord and LSBWord are joined in the VarOut variable.
Defining variables
LD LSBWord
ST FBData.LSW (* Transfer the LSW variable to input *)
LD FBData.Out
ST VarOut (* Transfer output to variable *)
Type Library
7.4.9 ToLower, Uppercase to lowercase letter conversion
Function eLLabUtyLib_C030
Function parameters:
Char (USINT) Character to convert.
Return value:
(USINT)
Character in lowercase format.
Examples
The Upper variable is converted to the corresponding lowercase character and transferred to Lower variable. The init
value 16#41, which corresponds to the letter 'A', is converted to the value 16#61, which corresponds to the letter 'a'.
Defining variables
LD example
IL example
LD Upper (* Uppercase letter *)
ToLower (* Uppercase to lowercase letter conversion *)
ST Lower (* Lowercase letter *)
ST example
Lower:=ToLower(Upper); (* Uppercase to lowercase letter conversion *)
Type Library
7.4.10 ToUpper, Lowercase to uppercase letter conversion
Function eLLabUtyLib_C030
Function parameters:
Char (USINT) Character to convert.
Return value:
(USINT)
Character in uppercase format.
Examples
The Lower variable is converted to the corresponding uppercase character and transferred to Upper variable. The init
value 16#61, which corresponds to the letter 'a', is converted to the value 16#41, which corresponds to the letter 'A'.
Defining variables
LD example
IL example
LD Lower (* Lowercase letter *)
ToUpper (* Lowercase to uppercase letter conversion *)
ST Upper (* Lowercase letter *)
ST example
Upper:=ToUpper(Lower); (* Lowercase to uppercase letter conversion *)
Type Library
7.4.11 LEArrayToVar, Little endian array to variable conversion
Function eLLabUtyLib_C030
This function acquires the value from a little endian (MSB – LSB) array Source and
transfers it to the destination variable Destination, according to the type defined in Type
variable.
Function parameters:
Type (USINT) Variable type as defined in the Variable types definition table.
Destination (@USINT) Destination variable address.
Source (@USINT) Source array address.
Return value:
(BOOL)
FALSE: Wrong variable type, TRUE: Conversion Ok.
Examples
The value "1, 2, 3, 4" in the LEArray array is converted into Variable, after conversion the variable will have the value
16 # 01020304.
Defining variables
LD example
Type Library
7.4.12 BEArrayToVar, Big endian array to variable conversion
Function eLLabUtyLib_C030
This function acquires the value from a big endian (LSB – MSB) array Source and
transfers it to the destination variable Destination, according to the type defined in Type
variable.
Function parameters:
Type (USINT) Variable type as defined in the Variable types definition table.
Destination (@USINT) Destination variable address.
Source (@USINT) Source array address.
Return value:
(BOOL)
FALSE: Wrong variable type, TRUE: Conversion Ok.
Examples
The value "4, 3, 2, 1" in the BEArray array is converted into Variable, after conversion the variable will have the value
16 # 01020304.
Defining variables
LD example
Type Library
7.4.13 VarToLEArray, variable to little endian array conversion
Function eLLabUtyLib_C030
This function transfers the value of a Source variable based on the Type defined, in an
Destination array using the little endian format (MSB – LSB).
Function parameters:
Type (USINT) Variable type as defined in the Variable types definition table.
Destination (@USINT) Destination array address.
Source (@USINT) Source variable address.
Return value:
(BOOL)
FALSE: Wrong variable type, TRUE: Conversion Ok.
Examples
The value of the Source variable is converted to the little endian (MSB – LSB) Destination array. The example also
reports the Watch window with the displayed values.
Defining variables
FBD example
Type Library
7.4.14 VarToBEArray, variable to big endian array conversion
Function eLLabUtyLib_C030
This function transfers the value of a Source variable based on the Type defined, in an
Destination array using the big endian format (LSB – MSB).
Function parameters:
Type (USINT) Variable type as defined in the Variable types definition table.
Destination (@USINT) Destination array address.
Source (@USINT) Source variable address.
Return value:
(BOOL)
FALSE: Wrong variable type, TRUE: Conversion Ok.
Examples
The value of the Source variable is converted to the big endian (LSB – MSB) Destination array. The example also
reports the Watch window with the displayed values.
Defining variables
FBD example
This function returns the system time expressed in microseconds. Using the Cmd value, it is
possible to define if you want to have the current system time (Cmd:=TRUE) or the one
stored with the previous execution of the function (Cmd:=FALSE). The count starts from 0
and after 4294 seconds resets.
Function parameters:
Cmd (BOOL) Allows to select the returned time.
TRUE: The actual time is saved and returned.
FALSE: The saved time (saved from the previous call with Cmd:=TRUE) is returned.
Return value:
(UDINT)
System time in μS.
Examples
It is calculated the time that the digital input Di00M00 remains in the activated condition..
Defining variables
END_IF;
Timeout calculation
Since the value of system time returned by the function an UDINT number incremented each μS, and the maximum
value to zero does overflow, you can not make direct comparisons with the reference time, but you should always make
the difference.
The following example the Timeout is activated if the Di00M00 input remains active for more than a second.
IF NOT(Di00M00) THEN TimeBf:=SysGetSysTime(TRUE);
ELSE IF ((SysGetSysTime(TRUE)-TimeBf) >= 1000000) THEN Timeout:=TRUE; END_IF;
END_IF;
The same example written in this way does not work properly.
IF NOT(Di00M00) THEN TimeBf:=SysGetSysTime(TRUE);
ELSE IF (SysGetSysTime(TRUE) >= (TimeBf+1000000)) THEN Timeout:=TRUE; END_IF;
END_IF;
A simple chronometer
This example creates a simple chronometer to measure the time between a start command and a stop. For example,
using two photocells one on the start line and one on the stop the of a path, it is possible to calculate the travel time
expressed in μS.
Activating the Di00M00 start input, the system time is saved in the StartTime variable. By activating the Di01M00 stop
input, the time elapsed between the start and stop is calculated. The calculated time is saved in the DelayTime
variable.
Defining variables
LD example (PTP119A000)
Type Library
7.5.2 SysSetTaskLpTime, set task loop time
Function XTarget_07_0
This feature allows you to set the execution time of PLC tasks. There are two settable
tasks: the slow task (ID_TASK_SLOW) and the fast task (ID_TASK_FAST). Each of
these tasks can be assigned an execution time.
If the set time is not included in the defined range or if the ratio of task execution times
fast than the slow are not consistent, the function does not change the time of execution
and returns FALSE. The following are the ranges of time defined for the various tasks.
ID_TASK_FAST Range from 100 μS to 10 mS
ID_TASK_SLOW Range from 1 to 100 mS
Function parameters:
TaskID (USINT) Identifies the task to which you want to set the execution time as defined in the Task ID.
Time (UDINT) Indicates the value of task execution time expressed in μS.
Return value:
(BOOL)
TRUE: If function successful.
FALSE: If an error occurs running, such as incorrect parameters.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9948990 Not yet implemented in the simulator.
Examples
Activating the Di00M00 input, an execution time of 5 ms is set for the task PlcFast.
Warning! To change the default execution time of tasks, you should execute the function in the boot task.
Defining variables
ST example
Enabled:=Di00M00; (* Function enabled *)
IF Di00M00 THEN
ExecutionOk:=SysSetTaskLpTime(TaskID:=ID_TASK_FAST, Time:=5000); (* Function execution ok *)
END_IF;
Type Library
7.5.3 SysGetRandom, get random number
Function XTarget_07_0
This function returns a random number between 0.0 and 1.0. With the value of Cmd you can
define whether you want a new random number (Cmd:=TRUE) or the one stored with the
previous execution of the function (Cmd:=FALSE).
Function parameters:
Cmd (BOOL) Indicates the random number returned.
TRUE: Is saved and returned a new random number.
FALSE: The number returned is the number saved from the previous call with Cmd:=TRUE.
Return value:
(REAL)
A random number in the range from 0.0 to 1.0.
Examples
Activating the Di00M00 digital input, is sent on the serial port COM0 a sequence of 10 random numbers.
Defining variables
IF (Di00M00) THEN
By connecting a terminal set to 115200,8,n,1, on serial port COM0, we will see a list of type:
Rn:437
Rn:488
Rn:898
...
Rn:261
Rn:944
Type Library
7.5.4 SysGetLastError, get last error
Function XTarget_07_0
This function returns the last error number reported by a function and/or a function
block. You must execute this function on fault bit activation out from function and/or
function block. Setting Cmd, it is possible to choice if you want to have the present
value of the last error (Cmd:=TRUE) or the one stored with the previous execution of
the function (Cmd:=FALSE).
Function parameters:
Cmd (BOOL) Indicates the error number returned.
TRUE: It returns the last error value.
FALSE: The number returned is the number saved from the previous call with Cmd:=TRUE.
Return value:
(UDINT)
The number of the last error found
Examples
It is saved the error during the execution of the SysGetPhrDI function block. In case of error, the error number is
transferred into the Error variable.
Defining variables
LD example
Type Library
7.5.5 SysPCodeAccept, accepts the protection code
Function XTarget_07_0
Some features of the program and/or function blocks may be protected by a code that must
be ordered separately. To enable the execution of the function and/or function block you
must unlock the code with this function.
The function checks the provided code and returns TRUE if the code is accepted. See the
functions and function blocks protection chapter for further information.
Function parameters:
Code (STRING[20]) Protection code.
Return value:
(BOOL)
TRUE: Code ID verified its unlocked.
FALSE: Code not verified.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9991100 Wrong Code.
9991990 Not yet implemented in the simulator.
Examples
It is showed a simple program that executes control over code "abcdefghijklmnopqrst". If the code is correct the
CodeAccepted variable is activated.
Defining variables
LD example (PTP116A000,LD_SysPCodeAccept)
ST example
(* Check the protection code. *)
Type Library
7.5.6 SysCalcCrc, CRC calculation
Function XTarget_12_0
Questa funzione funzione esegue il calcolo del CRC Cyclic Redundancy Check, (Controllo
Ciclico di Ridondanza) su di un'area dati. Il calcolo è effettuato secondo il tipo di CRC indicato
nel parametro CrcType.
Occorre passare alla funzione l'indirizzo del buffer di memoria Buf ed il numero di bytes
ByteNr su cui eseguire il calcolo del CRC. Occorre anche indicare un valore di inizializzazione
del calcolo che cambia in funzione del tipo di CRC calcolato.
Parametri funzione:
Buf (@USINT) Indirizzo dell'area di memoria su cui eseguire il calcolo del CRC.
ByteNr (UINT) Numero di bytes su cui eseguire il calcolo del CRC a partire dall'indirizzo definito in Buf.
CRCIni (UINT) Valore di inizializzazione del CRC da calcolare.
CRCType (UISNT) Tipo di CRC (1: Modbus RTU)
La funzione ritorna:
(UDINT)
Valore CRC calcolato.
Codici di errore
In caso di errore con SysGetLastError è possibile rilevare il codice di errore.
9938100 Tipo CRC errato.
Esempi
Viene calcolato il CRC di un frame modbus Rtu per il comando di lettura registri Read holding registers. Il valore del
CRC calcolato è 17466 (16#443A).
Definizione variabili
Type Library
7.5.7 SysMAlloc, memory allocation
Function XTarget_07_0
This function allocates a memory space of the size in bytes defined by Size parameter. The
function returns the pointer to the allocated memory space.
The memory is allocated in system memory and then does not use the memory available to the
user program. In the event that there is not room in memory for the defined buffer allocation, the function returns NULL.
Function parameters:
Size (UDINT) Size in bytes of the area to allocate.
Return value:
(@USINT)
Address allocation buffer. NULL if there is no space to allocate the buffer.
Error codes
If an error occurs the function returns NULL and SysGetLastError can detect the error code.
9947990 Not yet implemented in the simulator.
Examples
On rising edge of Di00M00 input, the Counter variable is incremented and the value is formatted on StringOut array.
The value in StringOut is then sent to the serial port COM0.
Defining variables
(* Here at first program execution loop allocate memory and open COM. *)
IF (SysFirstLoop) THEN
StringOut:=SysMAlloc(16); (* String output pointer *)
Fp:=Sysfopen('COM0', 'rw'); (* Port COM0 file pointer *)
END_IF;
IF (Di00M00) THEN
Counter:=Counter+1; (* Counter *)
NrOfChars:=SysVarsnprintf(StringOut, 32, 'Counter:%04d$r$n', UDINT_TYPE, ADR(Counter));
Type Library
7.5.8 SysRMAlloc, relocatable memory allocation
Function XTarget_12_0
Questa funzione esegue l'allocazione di uno spazio di memoria della dimensione in byte
definita da parametro Size. L'indirizzo alla memoria allocata è salvato nella variabile DataPtr.
La funzione ritorna FALSE se errore allocazione e TRUE se memoria allocata.
La memoria è allocata nella memoria di sistema e quindi non utilizza la memoria a
disposizione del programma utente. La memoria allocata viene automaticamente rilocata dal sistema operativo per
ottimizzare lo spazio. Quindi prima di utilizzarla occorre sempre fare riferimento all'indirizzo memorizzato in DataPtr.
Parametri funzione:
Size (UDINT) Dimensione in bytes dell'area da allocare.
DataPtr (UDINT) Buffer indirizzo memoria allocata.
La funzione ritorna:
(BOOL)
FALSE: Errore allocazione memoria, TRUE: Memoria allocata
Codici di errore
In caso di errore la funzione torna NULL e con SysGetLastError è possibile rilevare il codice di errore.
9933100 Funzione eseguita in task fast.
9933110 Valore di Size errato.
9933990 Non implementata nel simulatore.
Esempi
Su fronte attivazione ingresso Di00M00 viene incrementata la variabile Counter e la stampa del suo valore trasferita
nell'array StringOut. Il valore presente in StringOut viene poi inviato sulla porta seriale COM0.
Definizione variabili
IF (Di00M00) THEN
Counter:=Counter+1; (* Counter *)
Type Library
7.5.9 SysRMFree, relocatable memory free
Function XTarget_12
Codici di errore
In caso di errore la funzione torna NULL e con SysGetLastError è possibile rilevare il codice di errore.
9934100 Funzione eseguita in task fast.
9934990 Non implementata nel simulatore.
Esempi
Vedere esempio fornito con funzione SysRMAlloc.
Type Library
7.5.10 SysGetEndianness, get the system endianness
Function XTarget_12_0
Type Library
7.5.11 SysGetUTCDateTime, get the system Date/Time on UTC
Function XTarget_12_0
Type Library
7.5.12 SysSetUTCDateTime, set the system Date/Time on UTC
Function XTarget_12_0
Type Library
7.5.13 SysTimeZoneAdj, adjust date and time
Function XTarget_12_0
Parametri funzione:
UTCDateTime (UDINT) Valore di Date/Time in epoch time (UTC).
TimeZone (SINT) Fuso orario numero che indica la differenza in ore dell'ora locale rispetto al Tempo Coordinato
Universale (UTC) riferito al meridiano di Greenwich. Per l'Italia il valore da definire è +1.
DaylightZone (USINT) Zona di cambio ora legale, il sistema provvede automaticamente al cambio di ora in base alla
zona definita. Le zone sono 3 (Per l'Italia occorre impostare 1).
Codici di errore
In caso di errore la funzione torna FALSE e con SysGetLastError è possibile rilevare il codice di errore.
9940100 Errore TimeZone
9940110 Errore Daylight
Esempi
Ad ogni secondo viene calcolato il valore di Data/Ora locale per l'Italia.
Definizione variabili
Type Library
7.5.14 SysSpyData, system spy data
Function XTarget_11_0
This function allows to send data to the spy console (Accessible by Telnet with SpyData
command). You can define the way how the spy data is displayed Mode and a Label returned
in the spy string.
The TFlags parameter defines a 32 bits pattern which is used as a trigger for the data display
in the Telnet spy console.
By executing the function with all parameters to "0" is checked the space in the Telnet spy
console. The function returns TRUE if there is space to save the spy record and FALSE if the console is busy.
Function parameters:
Mode (USINT) Defines the way how the spy data is displayed, Spy mode.
TFlags (UDINT) Defines a pattern which is used as a trigger for the data display.
Label (@USINT) Label returned in the spy string.
DPtr (@USINT) Pointer to data to spy
La funzione ritorna:
(BOOL)
TRUE: Spy available. FALSE: Spy console busy.
Error codes
If an error occurs, with SysGetLastError you can detect the error code.
9950100 Function executed in task fast or slow.
9950200 Memory allocation error.
9950990 Not yet implemented in the simulator.
Spy record
The spy record appears in the spy console with a total length of 80 characters, typically is a record of the type:
00:00:00(0000)|Label|Spy data string--------------------------------------------
The time and the delay by the previous spy records fields have a constant length (15 characters). Field Label and spy
data can reach a total of 65 characters.
Example
This sample program sends to each second three records to the spy console.
Defining variables
Spy console
To activate the spy console, you must activate aTelnet connection to the system, (Refer to the SlimLine CPU's Telnet
commands reference manual). With the SpyData command you activate the spy console and displays the various data
records.
This function block performs the conversion of data expressed in epoch time. It should provide
the epoch time value as present in the SysDateTime system variable. Output from the function
block will have date values expressed in the format Day/Month/Year and
Time:Minutes:Seconds.
EpochTime (UDINT) You must specify the date expressed in epoch time.
Done (BOOL) Activated at the end of conversion.
Fault (BOOL) Conversion error. Is activated in case of error in the conversion.
Year (UINT) Return the year value (Range from 1970 to 2099)
Month (USINT) Return the month of year (Range from 1 to 12)
Day (USINT) Return the day of month (Range from 1 to 31)
WeekDay (USINT) Return the weekday value (Range from 0 to 6)
0: Sunday, 1:Monday, 2:Tuesday, 3:Wednesday, 4:Thursday, 5:Friday, 6:Saturday
Hour (USINT) Return the hour value (Range from 0 to 23)
Minute (USINT) Return the minute value (Range from 0 to 59)
Second (USINT) Return the seconds value (Range from 0 to 59)
Error codes
If an error occurs the Fault output is activated and SysGetLastError can detect the error code.
9986050 Function block allocation error.
9986060 Function block version error.
Examples
It is converted the epoch time value from SysDateTime variable to year, month and day variables.
Defining variables
LD SysDateTime
ST FB_SysETimeToDate.EpochTime
LD FB_SysETimeToDate.Year
ST Year
LD FB_SysETimeToDate.Month
ST Month
LD FB_SysETimeToDate.Day
ST Day
FB_SysETimeToDate.EpochTime:=SysDateTime;
FB_SysETimeToDate();
Year:=FB_SysETimeToDate.Year; (* Year *)
Month:=FB_SysETimeToDate.Month; (* Month *)
Day:=FB_SysETimeToDate.Day; (* Day *)
Type Library
7.6.2 SysDateToETime, date to epoch time conversion
FB XTarget_07_0
This function block performs the conversion of date-time in epoch time. You must provide the
date and time input and in the function block output, you will have a value in epoch time.
Year (UINT) Define the year value (Range from 1970 to 2099).
Month (USINT) Define the month of the year (Range from 1 to 12).
Day (USINT) Define the day of month (Range from 1 to 31).
Hour (USINT) Define the hour value (Range from 0 to 23).
Minute (USINT) Define the minute value(Range from 0 to 59).
Second (USINT) Define the second value (Range from 0 to 59).
Done (BOOL) Activated at the end of conversion.
Fault (BOOL) Conversion error. Is activated in case of error in the conversion.
EpochTime (UDINT) Converted epoch time value
Error codes
If an error occurs the Fault output is activated and SysGetLastError can detect the error code.
9987050 Function block allocation error.
9987060 Function block version error.
9987200 Errore during function block execution.
Examples
The date-time value is converted in epoch time. Defining the value of such date and time 9/4/2010 14:20:15 will output
the value 1270822815.
Defining variables
LD Year
ST FB_SysDateToEtime.Year
LD Month
ST FB_SysDateToEtime.Month
LD Day
ST FB_SysDateToEtime.Day
LD FB_SysDateToEtime.EpochTime
ST EpochTime
FB_SysDateToEtime.Year:=Year;
FB_SysDateToEtime.Month:=Month;
FB_SysDateToEtime.Day:=Day;
FB_SysDateToEtime(); (* Call the SysDateToEtime function block *)
EpochTime:=FB_SysDateToEtime.EpochTime; (* Epoch time *)
This function allows the opening of a resource specified by the FName parameter, linking it
with a stream of data usable in subsequent calls to the I/O functions. The function returns the
pointer to the resource.
If the resource specified is already open or the name of the resource is incorrect, the function
returns NULL. If you are opening a disk file to create it, make sure the disk is formatted.
Function parameter:
FName (STRING[20]) Name of the resource to use.
Name Resource
Mode (STRING[4]) Indicates how the resource is open: r=read, w=write a=append. For serial ports, use 'rw'. To create a
file on disk, you should try opening with 'w' or 'a'. The opening with 'w' on an existing file, erase its
contents. The opening with 'r' or 'w' position the position indicator of the stream at the beginning of
the file. Opening with 'a' positions it at the end.
Return value:
(FILEP) Pointer to resource.
NULL: In case of error.
Error codes
If an error occurs the function returns with NULL and SysGetLastError can detect the error code.
9996100 The FName resource has wrong length.
9996110 The FName resource has wrong length.
9996200~2 Impossible to use port from user program.
9996990 Not yet Implemented in the simulator.
Example
The serial port is open in read/write mode.
Defining variables
LD example
Type Library
7.7.2 SysFIsOpen, get the file open status
Function XTarget_12_0
Codici di errore
In caso di errore la funzione torna con EOF e con SysGetLastError è possibile rilevare il codice di errore.
9973990 Non implementata nel simulatore.
Esempi
Viene aperta e successivamente chiusa la porta seriale COM0. Se la porta è correttamente chiusa viene attivata l'uscita
Do01M00.
Definizione variabili
IF (SysFIsOpen(Fp)) THEN
Do01M00:=(Sysfclose(Fp) <> EOF); (* Output is set if port is closed *)
END_IF;
Type Library
7.7.3 Sysfclose, file close
Function XTarget_07_0
This function allows closing the connection to the resource indicated by the File parameter
previously opened by the Sysfopen function.
If case of error, the function returns EOF.
Function parameters:
File (FILEP) Stream returned from Sysfopen function.
Return value:
(INT)
0: If execution ok.
EOF: In case of error.
Error codes
If an error occurs the function returns with EOF and SysGetLastError can detect the error code.
9973100 I/O terminal used in task fast or slow.
9973200 Error closing resource.
9973990 Not yet Implemented in the simulator.
Examples
The serial port COM0 is opened and then closed. If the port is open Do00M00 output is activated. If the port is correctly
closed Do01M00 output is activated.Viene aperta e successivamente chiusa la porta seriale COM0.
Defining variables
Type Library
7.7.4 Sysfgetc, get character from file
Function XTarget_07_0
This function returns a character from the stream indicated by the File parameter previously
opened by the Sysfopen function.
The function returns the character read from the stream. If an error occurs or if no data available
from the stream, the function returns EOF. To make sure that there are characters from the stream
you can use the SysGetIChars function that returns they number.
Function parameters:
File (FILEP) Stream returned by Sysfopen function.
Return value:
(INT)
Read character from stream.
EOF: In case of error or no data available from stream.
Error codes
If an error occurs the function returns with EOF and SysGetLastError can detect the error code.
9972100 I/O terminal used in task fast or slow.
9972990 Not yet Implemented in the simulator.
Examples
Serial port COM0 is opened and checked if there are characters available. If at least one character is available it is read
and transferred into the Ch.
Defining variables
Type Library
7.7.5 Sysfputc, put character to file
Function XTarget_07_0
This function send a character into the stream indicated by the File parameter previously opened by
the Sysfopen function.
The function returns the character written to the stream. In case of error or if the stream does not
accept the data, the function returns EOF. To ensure that there is room to accept the character to the
stream, you can use the SysGetOSpace function that returns the available space.
Function parameter:
Ch (INT) Character to send to stream.
File (FILEP) Stream returned by Sysfopen function.
Return value:
(INT)
Character written to stream. EOF: In case of error or no data available from stream.In caso di errore o se lo
stream non accetta il dato.
Error codes
If an error occurs the function returns with EOF and SysGetLastError can detect the error code.
9971100 I/O terminal used in task fast or slow.
9971990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that performs the echo of characters received from the serial port COM0. The COM0
serial port is opened and checked and if there are characters available. If at least one character is available it is read
and subsequent written.
Defining variables
Using the I/O terminal functions, it is possible to create a simple program that performs the echo of character received
from the serial port COM0. The port is opened at 19200, e, 8, 1. All characters received are echoed.
Definizione variabili
Type Library
7.7.6 Sysfread, read data from file
Function XTarget_07_0
This function reads a specified number of strings of defined length, from the stream indicated by
the File parameter previously opened by the Sysfopen function.
The function returns the number of read data strings. If in the stream there are not enough string
to meet the parameters, it returns fewer string than the defined value.
Function parameter:
Buf (@STRING) Address of string where to store the read strings.
Size (INT) Length in character of the strings to read.
Count (INT) Number of strings to read.
File (FILEP) Stream returned by Sysfopen function.
Return value:
(INT)
Number of strings read. If the return value is less than Count, mean that there not were enough data in
the stream.
Error codes
If an error occurs the function returns 0 and SysGetLastError can detect the error code.
9970100 I/O terminal used in task fast or slow.
9970990 Not yet Implemented in the simulator.
Examples
At least 5 characters are waiting from the serial port and when received, a string of 5 characters (5 strings of 1
character) is read. The string read is transferred into the variable RxString and then sent to the serial port. Note that
also in transmission a string of 5 characters (1 string of 5 characters) is sent.
Defining variables
(* Here wait until at least 5 chars are received and echoes them. *)
Type Library
7.7.7 Sysfwrite, write data to file
Function XTarget_07_0
This function write a specified number of strings of defined length, to the stream indicated by the
File parameter previously opened by the Sysfopen function.
The function returns the number of written data strings. If in the stream there are not enough
space to store strings defined by parameters, it returns fewer string number than the defined
value.
Function parameter:
Buf (@STRING) Address of string to write.
Size (INT) Length in character of the strings to write.
Count (INT) Number of strings to write.
File (FILEP) Stream returned by Sysfopen function.
La funzione ritorna:
(INT)
Number of strings written. If the return value is less than Count, there was not enough space in the
stream.
Error codes
If an error occurs the function returns 0 and SysGetLastError can detect the error code.
9969100 I/O terminal used in task fast or slow.
9969990 Not yet Implemented in the simulator.
Examples
At least 5 characters are waiting from the serial port and when received, a string of 5 characters (5 strings of 1
character) is read. The string read is transferred into the variable RxString and then sent to the serial port. Note that
also in transmission a string of 5 characters (1 string of 5 characters) is sent.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
(* Here wait until at least 5 chars are received and echoes them. *)
Type Library
7.7.8 SysFGetIChars, get input available characters from file
Function XTarget_07_0
Error codes
If an error occurs the function returns 0 and SysGetLastError can detect the error code.
9968100 I/O terminal used in task fast or slow.
9968990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that performs the echo of characters received from the serial port COM0. The COM0
serial port is opened and checked if there are available character. If at least one character is available, it is read and
subsequent retransmitted.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
Type Library
7.7.9 SysFGetOSpace, get output available space on file
Function XTarget_07_0
Error codes
If an error occurs the function returns 0 and SysGetLastError can detect the error code.
9967100 I/O terminal used in task fast or slow.
9967990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that performs the echo of characters received from the serial port COM0. The COM0
serial port is opened and checked if there are available character. If at least one character is available, it is read and
subsequent retransmitted.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
Type Library
7.7.10 SysFGetIBfSize, get file Rx input buffer size
Function XTarget_07_0
Error codes
If an error occurs the function returns 0 and SysGetLastError can detect the error code.
9966100 I/O terminal used in task fast or slow.
9966990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that returns the size of the input buffer (receive) of COM2 serial port. The returned value
in number of characters (bytes) is transferred to the Space variable.
Defining variables
LD example
Type Library
7.7.11 SysFGetOBfSize, get file Tx output buffer size
Function XTarget_12_0
Error codes
If an error occurs the function returns 0 and SysGetLastError can detect the error code.
9965100 I/O terminal used in task fast or slow.
9965990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that returns the size of the output buffer (transmit) of COM2 serial port. The returned
value in number of characters (bytes) is transferred to the Space variable.
Defining variables
LD example
Type Library
7.7.12 SysFIBfClear, file input buffer clear
Function XTarget_07_0
This function deletes all the input characters in the stream indicated by the File parameter
previously opened by the Sysfopen function.
If an error occurs the function returns FALSE.
Function parameters:
File (FILEP) Stream returned by Sysfopen function.
Return value:
(BOOL)
FALSE: Execution error.
TRUE: Execution ok.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9964100 I/O terminal used in task fast or slow.
9964990 Not yet Implemented in the simulator.
Examples
If Di00M00 input is active, all characters from the serial port input will be deleted and Do00M00 activated.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
Type Library
7.7.13 SysFOBfClear, file output buffer clear
Function XTarget_07_0
This function deletes all the output characters in the stream indicated by the File parameter
previously opened by the Sysfopen function.
If an error occurs the function returns FALSE.
Function parameters:
File Stream returned by Sysfopen function.
(FILEP)
Return value:
(BOOL)
FALSE: Execution error.
TRUE: Execution ok.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9963100 I/O terminal used in task fast or slow.
9963990 Not yet Implemented in the simulator.
Examples
If Di00M00 input is active, all characters from the serial port output will be deleted and Do00M00 activated.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
Type Library
7.7.14 SysFOBfFlush, file output buffer flush
Function XTarget_07_0
This function forces an immediate exit of the characters present in the output stream indicated
by the File parameter previously opened by the Sysfopen function.
If an error occurs the function returns FALSE.
Function parameters:
File (FILEP) Stream returned by Sysfopen function.
Return value:
(BOOL)
FALSE: Execution error.
TRUE: Execution ok.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9962100 I/O terminal used in task fast or slow.
9962990 Not yet Implemented in the simulator.
Examples
If Di00M00 input is active, all the characters in the output buffer of the serial port will be transmitted and the Do00M00
output activated.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
Type Library
7.7.15 SysVarfprintf, variable print to file
Function XTarget_07_0
This function prints a formatted variable on the File stream previously opened by the
Sysfopen function.
The Format string specifies the format to use to print the variable. In VarType there is the
variable type and in VarAdd there is the variable address.
The function return the number of characters written into the stream. EOF in case of error.
Function parameters:
File (FILEP) Stream returned by Sysfopen function.
Format (STRING[80]) It has two types of argument: ordinary characters that are copied into the output stream and
conversion specifications, denoted by the percent symbol (%) and a character that specifies the
format in which to print the defined variable.
VarType (USINT) Variable type, as indicated in the variable types definition table.
VarAdd (UDINT) Variable address.
Return value:
(INT)
Number of characters written into the stream. EOF in case of error.
Error codes
If an error occurs the function returns EOF and SysGetLastError can detect the error code.
9998010 File value not defined.
9968100 I/O terminal used in task fast or slow.
9998200 Variable type not managed. Check VarType.
9982990 Not yet Implemented in the simulator.
Examples
On rising edge of Di00M00 input, the Counter variable is increased and its value is sent to COM0 serial port. In the
NrOfChars variable, the number of sent characters to serial port is loaded.
Defining variables
IF (Di00M00) THEN
Counter:=Counter+1; (* Counter *)
NrOfChars:=SysVarfprintf(Fp, 'Counter:%04d$r$n', UDINT_TYPE, ADR(Counter));
END_IF;
END_IF;
END_IF;
Type Library
7.8.1 Sysremove, file remove
Function XTarget_07_0
This function performs the removal (deletion) of a file. Name must be defined in the file name to
be deleted by specifying the full path (Example Storage/File.txt).
If the delete operation is successful, the function returns TRUE; on failure it returns FALSE.
Function parameters:
Name (STRING[32]) Filename to delete
La funzione ritorna:
(BOOL)
FALSE: Execution error.
TRUE: Execution ok.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9961100 Function used in task fast or slow.
9961150 Error in the file name declaration.
9961160 Directory not accessible by "Admin" user.
9961200 Error deleting the file.
9961990 Not yet Implemented in the simulator.
Examples
On rising edge of the Di00M00 digital input, the File.txt file placed in the Storage directory, is deleted.
Defining variables
LD example
Type Library
7.8.2 Sysrename, file rename
Function XTarget_07_0
This function change the name of a file. In OldName the name of the file to be renamed
must be defined by specifying the full path (Example Storage/OldFile.txt). In NewName the
new name of the filemust be defined by specifying the full path (Example
Storage/NewFile.txt).
If the rename operation is successful, the function returns TRUE; on failure it returns FALSE.
Function parameters:
OldName (STRING[32]) Name of file to rename.
NewName (STRING[32]) New name to set to file.
Return value:
(BOOL)
FALSE: Execution error.
TRUE: Execution ok.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9960100 Function used in task fast or slow.
9960150 Error in the file OldName declaration.
9960160 OldName directory not accessible by "Admin" user.
9960170 Error in the file NewName declaration.
9960180 NewName directory not accessible by "Admin" user.
9960200 Error renaming the file.
9962990 Not yet Implemented in the simulator.
Examples
On rising edge of the Di00M00 digital input, the OldFile.txt file placed in the Storage directory is renamed. New
filename will be NewFile.txt.
Defining variables
LD example
Type Library
7.8.3 Sysfilelength, file lengh
Function XTarget_07_0
This function returns the length in bytes of a file. Name defines the name of the file that you
want to know the length specifying the full path (Example Storage/File.txt).
If the file is not present, the function returns -1.
Function parameters:
Name (STRING[32]) Name of the file that you want to know the length.
Return value:
(DINT)
File lenght (Bytes). EOF if file not found.
Error codes
If an error occurs the function returns EOF and SysGetLastError can detect the error code.
9959100 Function used in task fast or slow.
9959990 Not yet Implemented in the simulator.
Examples
On rising edge of the Di00M00 digital input, the lenght of File.txt file placed in the Storage directory is returned.
Definizione variabili
LD example
Type Library
7.8.4 Sysfseek, file seek
Function XTarget_07_0
This feature allows you to change the position indicator of the stream connected to the File stream
previously opened by the Sysfopen function.
Offset specifies the number of bytes from the origin, where should you put the position indicator.
Origin specifies the origin from which to move the position indicator.
The function returns the current value of the position indicator. In the case of positioning error, the
position indicator remains unchanged and the function returns EOF.
Function parameters:
File (FILEP) Stream returned by Sysfopen function.
Offset (DINT) Number of bytes from the origin, where should you put the position indicator.
Origin (INT) Specifies the origin from which to move the position indicator, FSeek origin definition.
Return value:
(INT)
Actual indicator position. EOF is error.
Error codes
If an error occurs the function returns EOF and SysGetLastError can detect the error code.
9958100 Function used in task fast or slow.
9958990 Not yet Implemented in the simulator.
Examples
On rising edge of the Di00M00 digital input, the position indicator will be placed at start of file File.txt placed in the
Storage directory.
Defining variables
LD example
Type Library
7.8.5 SysDirListing, directory listing
FB XTarget_10_0
This function executes the directory listing of the directory defined in PathName. By setting
the Init initializes the list of files and the first file found is returned. Ad every Next command a
new file is find in the selected directory.
If a file is found the Found output is activated for a loop and its name is returned in
FileName. Once all the files in the directory are listed, on a Next command is no longer
activated the Found output and FileName is blanked. The output IsDir is set if the listed file is
a subdirectory.
Init (BOOL) By activating it's initialized the index of the files in the specified directory.
Next (BOOL) By activating it's returned the name of the file pointed to by the index in the specified directory.
The index is increased by focusing the next file.
PathName (STING[32]) Directory to be listed. A filter can be set (I.e 'Storage\*.log').
Found (BOOL) It is activated for a loop if on Init or Next command was found a new file to be listed.
Fault (BOOL) It is activated for a loop on execution error.
IsDir (BOOL) It is activated for a loop if the returned file is a subdirectory.
Size (UDINT) File size (Bytes).
Time (UDINT) Last file modification date, Epoch time (UTC).
FileName (STING[16]) File name with the extension.
Error codes
If an error occurs the Fault output is activated and SysGetLastError can detect the error code.
9952050 Function block allocation error.
9952060 Relocatable memory space full. You can not run the FB.
9952070 Function block version error.
9952100 FB used in task fast or slow
9952200 Directory listing execution error.
9952990 Not yet Implemented in the simulator.
Examples
By activating the digital input Di00M00 the files pointer in the Storage directory is initialized. At each activation of the
digital input Di01M00 in File is returned a new file name in the directory. If a new file is returned, Ok is activated for a
loop, if it's a subdirectory will Dir is activated.
Defining variables
LD example
Type Library
7.9.1 SysSerialPort, manage serial port
FB XTarget_12_0
Codici di errore
In caso di errore la funzione torna FALSE e con SysGetLastError è possibile rilevare il codice di errore.
9946050 Errore allocazione blocco funzione.
9946060 Terminato spazio memoria rilocabile, non è possibile eseguire l''FB.
9946070 Errore versione blocco funzione.
9946100 Dimensione buffers o flush time errati.
9946110 Errore impostazione porta seriale.
9946120 Errore baudrate.
9946121 Errore parity.
9946122 Errore data bits.
9946123 Errore stop bits
9946124 Errore DTR
9946990 Non implementata nel simulatore.
Esempi
Nell'esempio è attivato un server in ascolto sulla porta seriale. Connettendosi in seriale alla COM0 inviando un carattere
se ne riceve l'echo.
Definizione variabili
Type Library
7.9.2 SysGetSerialMode, get serial mode
Function XTarget_07_0
This function returns the communication mode of the serial port connected to the File
parameter previously opened by the Sysfopen function.
In the Mode parameter must define the address of the SYSSERIALMODE data structure
where will be transferred the actual serial port settings. The function returns FALSE on
error.
Function parameter:
Mode (@SYSSERIALMODE) Address of SYSSERIALMODE structure where to copy the serial port settings.
File (FILEP) Stream returned by Sysfopen function.
Return value:
(BOOL)
FALSE: Execution error. TRUE: Execution ok.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9995010 File value not defined.
9995020 SYSSERIALMODE structure address not correct. Verify Mode.
9995100 ÷ 1 Execution error.
9995990 Not yet Implemented in the simulator.
Examples
On rising edge of the Di00M00 digital input, the settings of serial port COM0 are saved in the Sm variable and the
Do00M00 logic output is activated.
Defining variables
IF (Di00M00) THEN
Do00M00:=SysGetSerialMode(ADR(Sm), Fp);
END_IF;
END_IF;
END_IF;
Type Library
7.9.3 SysGetSerialCTS, get serial CTS signal status
Function XTarget_07_0
This function returns the status of the CTS signal of the serial port specified by File
previously opened by the Sysfopen function.
Function parameters:
File (FILEP) Serial port stream returned by Sysfopen function.
Return value:
(BOOL)
FALSE: CTS deactive. TRUE: CTS active.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9993010 File value not defined.
9993990 Not yet Implemented in the simulator.
Examples
The CTS status of COM0 serial port is copied to Do01M00 output.
Defining variables
LD example
Type Library
7.9.4 SysSetSerialDTR, set DTR signal status
Function XTarget_07_0
This function sets the state of the DTR signal of the serial port specified by File previously
opened by the Sysfopen function.
In order to handle the DTR signal, the serial port must be set with the DTRManagement of
SYSSERIALMODE structure to DTR_OFF.
Function parameters:
Status (BOOL) DTR status to set on serial port.
File (FILEP) Serial port stream returned by Sysfopen function.
Return value:
(BOOL)
FALSE: Execution error. TRUE: Execution ok.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9992010 File value not defined.
9992990 Not yet Implemented in the simulator.
Examples
The status of Di00M00 input is transferred to the DTR of serial port COM0.
Defining variables
LD example
Type Library
7.10.1 SysCANSetMode, set the CAN controller mode
Function XTarget_07_0
This function sets the CAN controller mode. It's possible to define the bit rate, the packet
filter and mask acceptance.
The function returns TRUE if successful, FALSE on error.
Function parameters:
BitRate (USINT) CAN bus bit rate definition, CAN bit rate definition.
Filter (UDINT) CAN packet acceptance filter.
Mask (UDINT) CAN packet acceptance mask.
Return value:
(BOOL)
TRUE: Successfully executed.
FALSE: If an error occurs, such as incorrect parameters.
Error codes
If an error occurs the function returns FALSE, using the SysGetLastError the error code can be detected.
9957005 Function not supported.
9957990 Not yet Implemented in the simulator.
Examples
It's shown a simple program that set the CAN controllers with bit rates to 125 kbps. All incoming packets are received by
the controller.
Defining variables
LD example
Type Library
7.10.2 SysIsCANRxTxAv, checks if CAN Rx or Tx is available
Function XTarget_07_0
Error codes
If an error occurs the function returns FALSE, using the SysGetLastError the error code can be detected.
9956005 Function not supported.
9956990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that makes the control if a CAN message is received, read it and send the structure of
the received message to the serial port COM0.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
IF (SysIsCANRxTxAv(FALSE)) THEN
IF (SysCANRxMsg(16#00000000, 16#00000000, ADR(CANMsg))) THEN
END_IF;
END_IF;
Type Library
7.10.3 SysCANRxMsg, receives a CAN message
Function XTarget_07_0
This function receives a CAN message and transfers it to the variable whose address is defined
in the Msg. It is possible to define a Mask and an ID to receive only CAN messages you want.
The function search on the stack of messages a message whose ID in logic AND with Mask,
match the ID in logic AND with Mask. The function returns TRUE if the message was received.
Function parameters:
Mask (UDINT) Mask code.
ID (UDINT) Messagge ID.
Msg (@SYSCANMESSAGE) Received message buffer address.
Return value:
(BOOL)
TRUE: Message received.
Error codes
If an error occurs the function returns FALSE, using the SysGetLastError the error code can be detected.
9955005 Function not supported.
9955990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that performs the reception of any CAN message and performs sending out to the serial
port COM0 of the structure of the received message.
Defining variables
ST example
(* Here the COM0 port is opened in read/write. *)
END_IF;
Type Library
7.10.4 SysCANTxMsg, transmit a CAN message
Function XTarget_07_0
This function sends a CAN message. We need to create the message and to pass its address
in Msg.
Function returns TRUE if the message was sent.
Function parameters:
Msg (@SYSCANMESSAGE) Buffer address of message to send.
Return value:
(BOOL)
TRUE: Message sent.
Error codes
If an error occurs the function returns FALSE, using the SysGetLastError the error code can be detected.
9954005 Function not supported.
9954990 Not yet Implemented in the simulator.
Examples
It is showed a simple program that performs the transmission of a CAN message.
Defining variables
ST example
(* Here check if there is a space in Tx buffer and send a CAN message. *)
IF (SysIsCANRxTxAv(TRUE)) THEN
CANMsg.RmReq:=FALSE; (* eFALSE:Data frame, eTRUE:Remote request *)
CANMsg.Length:=2; (* Data length *)
CANMsg.MsgID:=16#00000000; (* Message ID (FF:Bit 31) (11 or 29 Bit) *)
CANMsg.Data[0]:=16#01; (* Message data *)
CANMsg.Data[1]:=16#00; (* Message data *)
TxOk:=SysCANTxMsg(ADR(CANMsg)); (* Transmission Ok *)
END_IF;
This function returns the length (expressed in number of characters) of the string defined in Str.
Function parameters:
Str (@USINT) Pointer to string to return lenght.
Return value:
(INT)
Number of characters present in the string.
Examples
It is calculated the length of the string 'Hello!' and the number of characters in the string is passed in the Length
variable. The calculation result is 6.
Defining variables
LD example
Type Library
7.11.2 eFIND, string find
Function ePLCStdLib_B000
This function searches the position of the first occurrence of the string In2 in In1. If no occurrence is
found, the function returns 0.
If the string In2 is found in the string In1, then its position is returned.
Example: eFIND(In1:='abcd', In2:='bc'). The result is 2.
Function parameters:
In1 (@USINT) Pointer to string where to make search.
In1 (@USINT) Pointer to string to search.
Return value:
(INT)
Position of the first occurrence of In2 in In1. 0 if string not found.
Examples
It is searched the string 'lo' in string 'Hello world!'. The location found is 4 and is transferred to the variable Position.
Defining variables
ST example
(* Find the position where is StrToFind in StrSource. *)
StrSource:='Hello world!';
StrToFind:='lo';
Position:=eFIND(ADR(StrSource), ADR(StrToFind));
Type Library
7.11.3 MemSet, memory set
Function eLLabUtyLib_C030
This function set Size bytes of Buffer with the value defined in Value.
The function returns the number defined in Size.
Function parameters:
Buffer (@USINT) Pointer to memory buffer where to set Value.
Value (USINT) Value to set to memory buffer.
Size (UDINT) Number of bytes to set with Value starting from Buffer.
Return value:
(UDINT)
Size Value.
Examples
Set to zero all the bytes of the string StrBuffer writing the value 0 in its entire length.
Defining variables
ST example
(* The 'StrBuffer' variable is set to '0'. *)
Type Library
7.11.4 MemCopy, memory copy
Function eLLabUtyLib_C030
This function copies the number of bytes defined in Size starting from the memory area
pointed to by Source, to the area that starts at Destination.
The function returns the number defined in Size.
Function parameters:
Destination (@USINT) Pointer to destination buffer.
Source (@USINT) Pointer to source buffer.
Size (UDINT) Number of byte to be transferred
Return value:
(UDINT)
Size Value.
Examples
It's executed the copy of the SString in the DString. At the end of the resulting string will be "HelloHello.
Defining variables
ST example
(* The 'SString' is copied twice into 'DString'. *)
Type Library
7.11.5 SysVarsnprintf, variable print to string
Function XTarget_08_0
This function transfers in String the formatted variable. The formatted value returned in the
String variable, can not exceed the length defined in Size.
The Format string specifies the format in which to print the variable. VarType is the variable
type and VarAdd is its address.
The function returns the number of characters transferred to the String variable. EOF on
error.
Function parameters:
String (@USINT) Pointer to the string which must contain the printed results.
Size (UINT) Number of characters to be transferred into the String variable. The definite number is inclusive of
the code at the end of string '\0'. If the length of output string exceeds the Size bytes, it is truncated
to the number of bytes indicated.
Format (STRING[80]) It has two types of subjects: ordinary characters that are copied into the String variable output, and
conversion specifications, denoted by the symbol percent (%) and a character that specifies the
format in which to print the defined variable.
VarType (USINT) Variable type as indicated in the table variable types definition.
VarAdd (UDINT) Address of variabile.
Return value:
(INT)
Number of code characters including the end of string '\ 0' transferred to the String variable.
EOF: Error executing.
Error codes
If an error occurs the function returns EOF and SysGetLastError can detect the error code.
9997100 Variable type not managed. Check VarType.
9997200 The Size value, limits the format of the out string.
Examples
On rising edge of Di00M00 input, the Counter variable is increased and its value is formatted in StringOut. The value
in StringOut is then sent to the serial port COM0. NrOfChars is loaded with the number of characters formatted in
StringOut and sent out to the serial port.
Defining variables
IF (Di00M00) THEN
Counter:=Counter+1; (* Counter *)
NrOfChars:=SysVarsnprintf(ADR(StringOut), 32, 'Counter:%04d$r$n', UDINT_TYPE, ADR(Counter));
In this example, the merge is performed between prints value of two variables. Execute merge can be very useful to
have a single string containing printed value of several variables.
By putting the Result variable in debug, we will see the string Var[0]:12 Var[1]:34. Having blocked the printing to 12
characters the value of Var[0] will be printed correctly to a maximum of 4 digits (7 string characters, 4 string terminator
character '\0'). For values of Var[0] greater than 9999 will no longer print the least significant digits.
The value of Var[1] will be printed immediately after the value of Var[0]. Note the decreased offset of 1 to overwrite the
string terminator '\0'. To guarantee the printing of up to 4 for Var[1], has been used a Size of 13. The string of text starts
with a space character to separate it from the print out of the previous variable.
Defining variables
ST example
(* -------------------------------------------------------------------------- *)
(* EXECUTE A VARIABLES PRINT MERGE *)
(* -------------------------------------------------------------------------- *)
(* Print the variable values, merging them into a single string. *)
(* [End of file] *)
Type Library
7.11.6 SysLWVarsnprintf, variable print to string with append
Function XTarget_12_0
Codici di errore
In caso di errore la funzione torna con EOF e con SysGetLastError è possibile rilevare il codice di errore.
9993100 Tipo variabile non gestito, controllare VarType.
9932110 Lunghezza stringa è maggiore di Size (Impossibile eseguire la funzione).
9993200 Il valore di Size limita la formattazione della stringa in uscita.
Esempi
Vedere esempi della funzione SysVarsnprintf.
Type Library
7.11.7 SysVarsscanf, extracts values from string
Function XTarget_08_0
This function reads the String, and interprets it according to the specified Format.
The Format string specifies the format in which to interpret the variable. VarType indicates
the variable type and VarAdd its address.
The function returns TRUE if the variable was found, in other case FALSE.
Function parameters:
String (@USINT) Pointer to string to read.
Format (STRING[80]) It has two types of subjects: ordinary characters that are checked into the String input variable, and
conversion specifications, denoted by the symbol percent (%) and a character that specifies the
format in which to print the defined variable.
VarType (USINT) Variable type as indicated in the table variable types definition.
VarAdd (UDINT) Variable address.
Return value:
(BOOL)
TRUE: Variabile value acquired.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9999100 Variable type not managed. Check VarType.
Examples
It is showed a program that reads a InputString string init with text Value:123. On Di00M00 input rising edge, three
different functions are exected, all on InputString string but with different definitions for Format. The first two are
successful and variables Variable[0] and Variable[1] will be set with the value 123. The third will fail and the variable
Variable[2] will be reset.
Defining variables
IF (Di00M00) THEN
Result[0]:=SysVarsscanf(ADR(InputString), 'Value:%d', UDINT_TYPE, ADR(Variable[0]));
Result[1]:=SysVarsscanf(ADR(InputString)+6, '%d', UDINT_TYPE, ADR(Variable[1]));
Result[2]:=SysVarsscanf(ADR(InputString), '%d', UDINT_TYPE, ADR(Variable[2]));
END_IF;
END_IF;
Type Library
7.11.8 SysFWVarsscanf, extracts values from string with find
Function XTarget_12_0
Codici di errore
In caso di errore la funzione torna con FALSE e con SysGetLastError è possibile rilevare il codice di errore.
9999100 Tipo variabile non gestito, controllare VarType.
Esempi
Fare riferimento agli esempi dalla funzione SysVarVarsscanf.
This function executes the acquisition of informations from the peripheral modules. The
information indicated by InfoID is read from the Module extension module and is copied into
the string variable whose address is passed by Info.
Function return TRUE if ok, FALSE in other cases.
Function parameters:
Module (USINT) You must specify the module address from which to get informations (range from 0 to 15). The value
0 indicates the first extension module, 1 for the second and so on.
InfoID (USINT) You must specify the ID of required information.
Value Description
0 Return the product code
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9990100 Addressed Module not present.
9990110 InfoID not correct.
9990200 The required information is not supported by module.
9990210 Error during request of information from module.
9990990 Not yet Implemented in the simulator.
Examples
It is showed a program that reads the product code from extension module with address 0. The returned code is
transferred into the Info variable. The return of the function is transferred to the Do01M00 output.
Defining variables
LD example
This function block performs the acquisition of digital inputs from the peripheral modules. The
function block returns the status of digital inputs from the module specified by Address and using the
Mode defined.
To acquire the digital inputs on the CPU module, you must define 255 as Address and DI_8_LL as
Mode.
Address (USINT) You must specify the module address from which to acquire the digital inputs (range 0 to 255). A
value of 0 indicates the first extension module, 1 for the second and so on. The address 255
indicates the CPU module.
Mode (USINT) You must specify the mode of acquisition of the digital inputs, refer to Digital input mode.
Done (BOOL) Data acquired. Activated if the digital inputs acquisition, has terminated.
Fault (BOOL) Acquisition error. It is activated when an error occurs in the sequence of acquisition.
Value (UDINT) Returns the status of digital inputs acquired.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9985050 Function block allocation error.
9985070 Function block version error.
9985100 The module addressed with Address is not present.
9985110~24 The acquisition Mode is not correct.
9985200~13 Error during reading of module peripheral input.
Examples
It acquired the status of the 8 inputs low (from inp 0 to Inp 7) of the module with address 0. If data valid, the FBDone
variable is activated; if acquisition error, the FBFault variable is activated. The value obtained in the range 0x00 to
0xFF, is transferred into the InpValue variable.
Defining variables
LD 0
ST FBData.Address
LD DI_8_LL
ST FBData.Mode
CAL FBData
LD FBData.Value
ST InpValue
FBData.Address:=0;
FBData.Mode:=DI_8_LL;
FBData(); (* Execute FB *)
InpValue:=FBData.Value; (* Digital input value *)
This example is an evolution of the previous example. Using the ByteToBit function block, the status of the 8 low inputs
(from Inp 0 to Inp Inp 7) of the module with address 0, is copied on an array of BOOL.
Defining variables
This function block performs the setting of digital outputs on the peripheral modules addressed with
Address and using the Mode defined.
To not disturb the logic outputs management executed by the process image, in Mask it's possible to
define on what output you want to work. In practice, the FB will work only on output whose
corresponding bit of the mask is active.
To set the digital outputs on the CPU module, you must define 255 as Address and DO_8_LL as
Mode.
Address (USINT) You must specify the module address to which to set the digital outputs (range 0 to 255). A value of 0
indicates the first extension module, 1 for the second and so on. The address 255 indicates the CPU
module.
Mode (USINT) You must specify the mode of setting of the digital outputs, refer to Digital output mode.
Value (UDINT) Set the value to be transferred to the digital outputs.
Mask (UDINT) Digital output mask.
Done (BOOL) Data set. Is activated for a loop at the end of setting of the digital outputs.
Fault (BOOL) Error. It is activated when an error occurs in the settings sequence.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9984050 Function block allocation error.
9984060 Relocatable memory space full. You can not run the FB.
9984070 Function block version error.
9984100 The module addressed with Address is not present.
9984110~8 The acquisition Mode is not correct.
9984200~6 Error during execution of function block.
Examples
The value of the OutValue variable is transferred to the Out 0 of the module with address 0.
Defining variables
LD 0
ST FBData.Address
LD DO_8_LL
ST FBData.Mode
LD OutValue
LD FBData.Value
LD 16#00000001
LD FBData.Mask
CAL FBData
FBData.Address:=0;
FBData.Mode:=DO_8_LL;
FBData.Value:=OutValue; (* Digital ouput value *)
FBData.Mask:=16#00000001; (* Output mask *)
FBData(); (* Execute FB *)
This function block performs the acquisition of the analog input from the acquisition module. The
function block operates according to various methods of acquiring the analog module to which it
refers.
To acquire the analog inputs on the CPU module, you must define 255 as Address and
AD_VOLT_0_10_COMMON as Mode.
Address (USINT) You must specify the module address to which to acquire the analog inputs (range 0 to 255). A value
of 0 indicates the first extension module, 1 for the second and so on. The address 255 indicates the
CPU module.
Channel (USINT) You must specify the channel address on the extension module (range from 0x00 to 0x0F). If you set
a channel address that is not present, execution stops and the Fault bit is set.
Mode (USINT) You must specify the mode of analog acquisition, refer to Analog to digital mode.
Done (BOOL) Analog data acquired. Activated if the analog inputs acquisition, has terminated.
Fault (BOOL) Acquisition error. It is activated when an error occurs in the sequence of acquisition.
Value (REAL) Return the acquisition value expressed in units defined by mode of acquisition. It could be a NaN
(Not a Number) to indicate a problem in the acquisition, typically sensor failure.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9983050 Function block allocation error.
9983060 Relocatable memory space full. You can not run the FB.
9983070 Function block version error.
9983080 Impossible to initialize module.
9983100 The module addressed with Address is not present.
9983110~1 The addressed module does not support the analog input command.
9983150 The returned value is not correct.
9983200 The selected Mode is not supported by module.
9983210 Error during analog acquisition.
9983300 The selected Channel is not supported by module.
Examples
Acquisition from analog channel 0 of module 0 using 0-10 volts mode is executed. If the data is valid, the Do00M00
digital output is activated. If conversion error, the Do01M00 digital output is activated. The analogue data acquired in
the range from 0,000 to 9,999 is transferred into the variable AnaInp.
Defining variables
LD 0
ST FBData.Address (* Set module address *)
LD 0
ST FBData.Channel (* Set channel *)
LD AD_VOLT_0_10_COMMON
ST FBData.Mode (* Set acquisition mode *)
LD FBData.Done
ST Do00M00 (* The output is active if data is acquired *)
LD FBData.Fault
ST Do01M00 (* The output is active if execution fault *)
LD FBData.Value
ST AnaInp (* Store the acquired value *)
This function block performs the set of a value on the analog output module. The function block
manages a variety of ways depending on the analog module to which it refers.
Address (USINT) You must specify the address of the module to which to set the analog value (range from 0x00 to
0x0F). The value 0x00 indicates the first extension module, 0x01 the second and so on.
Channel (USINT) You must specify the channel address on the extension module (range from 0x00 to 0x0F). If you set
a channel address that is not present, execution stops and the Fault bit is set.
Mode (USINT) You must specify the mode of analog output, refer to Digital to analog mode.
Value (REAL) You must specify the output value in the unity defined by Mode.
Done (BOOL) Data set. Is activated for a loop at the end of setting of the analog output.
Fault (BOOL) Error. It is activated when an error occurs in the settings sequence.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9982050 Function block allocation error.
9982060 Relocatable memory space full. You can not run the FB.
9982070 Function block version error.
9982080 Impossible to init module.
9982100 The module addressed with Address is not present.
9982110~1 The addressed module does not support the analog output command.
9982150 The value to set is not correct.
9982200 The selected Mode is not supported by module.
9982210 Error during analog output.
Examples
The analog output on channel 0 of module 0 using 0-10 volts mode, is executed. If the data is valid, the Do00M00
digital output is activated. If conversion error, the Do01M00 digital output is activated. The data to set to analog output
in the range from 0,000 to 9,999 is present in the AnaOut variable.
Defining variables
LD 0
ST FBData.Address (* Set module address *)
LD 0
ST FBData.Channel (* Set channel *)
LD DA_VOLT_0_10
ST FBData.Mode (* Set management mode *)
LD AnaOut
ST FBData.Value (* Store the output value *)
LD FBData.Done
ST Do00M00 (* The output is active if data is set *)
LD FBData.Fault
ST Do01M00 (* The output is active if execution fault *)
This function block reads a counter. The function block can be used to capture the value of the
counter on the CPU module and the SlimLine modules that support the counter function.
It is possible to manage the reset and the reverse of the count value. According to the definition of
Mode, you can manage count on rising edge, falling edege or both edge of the input clock. If the
module that manages the counter support it, you can also define hardware commands (digital inputs)
to reset counter and to reverse counting.
Address (USINT) You must specify the module address from which to get counter value (range from 0 to 255). The
value 0 indicates the first extension module, 1 for the second and so on.
The address 255 indicates the CPU module.
If you set an address of a module that is not present, execution stops and the Fault bit is set.
Channel (USINT) You must specify the channel address on the module (range from 0 to 15).
If you set a channel address that is not present, execution stops and the Fault bit is set.
If an incorrect value is set, execution stops and the Fault bit is set.
RCount (BOOL) Reverse counting. If active, the Value is decreased every Clock; if deactive, it is increased every
Clock.
Reset (BOOL) When active, the Value is reset.
Done (BOOL) Counter value acquired. Active for a program loop at the end of acquisition.
Fault (BOOL) Acquisition error. It is activated when an error occurs in the sequence of acquisition.
Value (UDINT) Counter value.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9981050 Function block allocation error.
9981060 Relocatable memory space full. You can not run the FB.
9981070 Function block version error.
9981080 Impossible to initialize module.
9981100 The module addressed with Address is not present.
9981110 The defined Channel is not supported.
9981200~4 The defined Mode is not supported.
9981300~2 Error during reading of counter value from module.
9981990 Not yet Implemented in the simulator.
Examples
It is acquired the counter value from the SlimLine CPU module. Counting is performed on both sides of the clock input.
The count value is transferred into the Value variable. At the end of conversion, the Do01M00 digital output is activated.
If conversion error, the Do02M00 digital output is activated.
Activating the Di00M00 input, there is the reverse of the count. At each edge of the clock input, the count Value
decreases.
Activating the Di01M00 input, the count Value is reset.
Defining variables
LD example
This function block reads an encoder channel. The function block can only be used on systems
that have extension modules that support incremental encoders.
It is possible to manage the zero mark and to acquire quotes values on a gate signal.
Address (USINT) You must specify the module address from which to get encoder value (range from 0 to 15). The
value 0 indicates the first extension module, 1 for the second and so on. The address 255 indicates
the CPU module.
If you set an address of a module that is not present, execution stops and the Fault bit is set.
Channel (USINT) You must specify the channel address on the module (range from 0 to 15).
If you set a channel address that is not present, execution stops and the Fault bit is set.
RCount (BOOL) Reverse counting. Activating this input, it is inverted the EQuote increment related to the direction of
rotation of the encoder.
ZeroEn (BOOL) By activating this input, the EQuote will be reset at the passage of the encoder zero mark.
GateEn (BOOL) By activating this input, on the rising or falling edge (depending from Rgate) of Gate input, the
EQuote value will be copied in the GQuote value.
RGate (BOOL) Activating this input, the falling edge of Gate input will be used.
Done (BOOL) Encoder value acquired. Active for a program loop at the end of acquisition.
Fault (BOOL) Acquisition error. It is activated when an error occurs in the sequence of acquisition.
ZeroD (BOOL) Encoder zero mark acquired. It is activated when the zero mark input is detected. It is reset
deactivating the ZeroEn input.
GateD (BOOL) Encoder Gate acquired. Active for a program loop when the Gate signal is detected.
GQuote (UINT) Gate quote. This is the EQuote value stored on the edge selected for Gate signal.
EQuote (UINT) Encoder quote. This is the encoder quote value. When it reaches the minimum or maximum value,
there is the roll over.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9980050 Function block allocation error.
9980060 Relocatable memory space full. You can not run the FB.
9980070 Function block version error.
9980100 The module addressed with Address is not present.
9980110~2 The addressed module doesn't support the encoder commands.
9980200 The defined Mode is not supported by module.
9980210~2 Error during reading of encoder value from module.
9980990 Not yet Implemented in the simulator.
Examples
It is acquired the encoder value from input channel 0 of module 0. The encoder value is transferred into the
EncoderQte variable. At the end of acquisition, the Do00M00 digital output is activated. If conversion error, the
Do01M00 digital output is activated.
Defining variables
LD 0
ST FBData.Address (* Set module address *)
LD 0
ST FBData.Channel (* Set channel *)
LD FALSE
ST FBData.RCount (* Reverse counting *)
ST FBData.GateEn (* Gate enable *)
ST FBData.RGate (* Reverse gate *)
LD FBData.Done
ST Do00M00 (* The output is active if data is acquired *)
LD FBData.Fault
ST Do01M00 (* The output is active if execution fault *)
LD FBData.GQuote
ST GateQte (* Gate quote *)
LD FBData.EQuote
ST EncoderQte (* Encoder quote *)
This function block sets the value of frequency and duty cycle of the PWM generator selected by
Address e Channel. The value range of frequency and duty cycle depends on the card used.
Setting the value of Frequency to 0 it disables the PWM and the output is forced based on the value
of Duty.
Duty <50: The output is set to FALSE.
Duty> = 50: The output is set to TRUE.
Address (USINT) You must specify the module address from which to get encoder value (range from 0 to 15). The
value 0 indicates the first extension module, 1 for the second and so on. The address 255 indicates
the CPU module.
If you set an address of a module that is not present, execution stops and the Fault bit is set.
Channel (USINT) You must specify the channel address on the module (range from 0 to 15).
If you set a channel address that is not present, execution stops and the Fault bit is set.
Frequency (REAL) Output frequency value (For range refer to the hardware manual of the card used). The value is
expressed in Hz.
Duty (REAL) Duty cycle output value (For range refer to the hardware manual of the card used). The value is
expressed in %.
Done (BOOL) PWM generator properly set.
Fault (BOOL) Execution error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9951050 Function block allocation error.
9951070 Function block version error.
9951100 The module addressed with Address is not present.
9951110 Channel number not present.
9951500 Execution error.
9951990 Not yet Implemented in the simulator.
Esempi
Is set output Out 0 of the CPU module to generate a PWM signal at 100 Hz with 50% duty cycle.
Defining variables
LD example
Function parameters:
Module (USINT) You must specify the module address from which to get value (range from 0 to 15). The value 0
indicates the first extension module, 1 for the second and so on.
RdAdd (UINT) Address of variable to read as allocated on the extension module.
VarType (USINT) Variable type as defined in the variable types definition table.
VarAdd (UDINT) Address of variable where to copy the read value.
Return value:
(BOOL)
FALSE: Execution error. TRUE: Execution ok.
Error codes
If an error occurs, the function return FALSE and SysGetLastError can detect the error code.
9989100 The module addressed with Module is not present.
9989110 The variable type VarType is not correct.
9989200 Error during read of variable value from module.
9989990 Not yet Implemented in the simulator.
Examples
By activating the Di00M00 input, the read of UDINT variable at address 16 of the extension module 0 is executed. The
value of the variable is copied to DB100 at offset 8.
Defining variables
LD example
Function parameters:
Module (USINT) You must specify the module address to which to write value (range from 0 to 15). The value 0
indicates the first extension module, 1 for the second and so on.
WrAdd (UINT) Address of variable to write as allocated on the extension module.
VarType (USINT) Variable type as defined in the variable types definition table.
VarAdd (UDINT) Address of variable where there is the value to write
Return value:
(BOOL)
FALSE: Execution error. TRUE: Execution ok.
Error codes
If an error occurs, the function return FALSE and SysGetLastError can detect the error code.
9988100 The module addressed with Module is not present.
9988110 The variable type VarType is not correct.
9988200 Error during write of variable value to module.
9988990 Not yet Implemented in the simulator.
Examples
By activating the Di00M00 input, the write of UDINT variable at address 16 on the extension module 0 is executed. The
value to write is in DB100 at offset 8.
Defining variables
LD example
This function manages the I2C extension bus. By using this function it's possible to manage
any component connected to the I2C extension bus.
Be careful, the I2C bus is used to access to extension modules to avoid to slow down
their access we suggest to manage I2C commands not longer than 4 bytes in writing
and reading. If needed to manage longer commands it is advisable to break the
command into multiple commands.
Function parameters:
Address (USINT) I2C address out of range, range is from 16#00 to 16#7F.
WrBytes (USINT) Number of bytes to write. 0 if only bus read.
WrBuffer (@USINT) Write data buffer address. NULL if only bus read.
RdBytes (USINT) Number of bytes to read. 0 if only bus write.
RdBuffer (@USINT) Read data buffer address. NULL if only bus write.
Return value:
(BOOL)
TRUE: Command executed.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
9953100 I2C address out of range (Value greather than 16#7F).
9953105 I2C address used by an extension module.
9953990 Not yet Implemented in the simulator.
Examples
In this example a simple program that reads and writes a PCF9670 I/O expander on I2C bus. The chip has address
16#38.
Defining variables
LD example
This function block manages the strain gauge acquisition it uses the SysGetAnInp
FB to acquire the analog input that reads the strain gauge. In Address and
Channel must be defined the analog input acquisition module parameters. In Mode
must be defined the appropriate strain gauges acquisition mode.
Before to operate it's important to calibrate the acquisition (Calibration values are
stored in OfsCalibration and FSCalibration variables). To calibrate the offset
connect the strain gauge and with no weight applied activate for a loop
DoOfsCalibration. For the full scale calibration apply a weight as possible next to
the full scale value to the strain gauge. The value of the applied weight must be
defined in FSReference , after a period of weight reading stabilization to activate for
a loop DoFSCalibration.
Mode must be set higher. But this formula must be respected: (SGaugeRatio x
PowS. x Mode) < PowS. Where PowS. is the strain gauge power supply. Example:
strain gauge with SGaugeRatio = 2mV/V and power supply 5V. With Mode =
AD_VIN_VREF_G_128 will be (2mV/V * 5V * 128) = 1280mV so under the 5V
power supply and so ok.
In FilterCf è possibile definire un coefficente di filtro sulla acquisizione del peso, più il valore è grande e più il valore di
peso è filtrato. Con 0, non c'è filtro lasciando la possibilità di inserire un proprio filtro personalizzato esterno.
In FilterCf you can define a filter coefficient on weight acquisition, more the value is great and more the weight value is
filtered. With 0, there is no filter so it is possible to insert an external custom filter.
Error codes
If an error occurs the function returns FALSE and SysGetLastError can detect the error code.
10045100 Mode value not correct.
Example
The program acquires a load cell with 1.956 m/V and full scale of 20 Kg. The cell is calibrated with a reference weight of
400 grams. Di00M00 enables the acquisition, inputs Di01M00 and Di02M00 allow to calibrate the cell (Caution
OfsCalibration and FSCalibration variables must be defined RETAIN). Weight is returned in the variable Weight.
Having defined SGaugeFullScale in Kg Value is also expressed in Kg.
Defining variables
LD example
This function block operates a blinking output with definable cycle time. By activating the
ENABLE input, the OUT output blinks with defined high and low cycle times.
ENABLE (BOOL) Function block enable. Activating it, the blinking of OUT output is handled. Deactivating it the OUT
output is reset.
TIMELOW (UDINT) Defines the time in which the OUT output is in low state. It is expressed in mS.
TIMEHIGH (UDINT) Defines the time in which the OUT output is in high state. It is expressed in mS.
OUT (BOOL) Blinking output.
Examples
Is set a blink with 100 ms in high state and 1000 ms in low state. Activating the Di00M00 digital input, the Do00M00
digital output blinks with the time defined.
Deactivating the Di00M00 digital input, the Do00M00 digital output resets immediately.
Defining variables
LD Di00M00
ST FB_BLINK.ENABLE (* Transfer the digital input to enable input *)
LD 1000
ST FB_BLINK.TIMELOW (* Set the time low *)
LD 100
ST FB_BLINK.TIMEHIGH (* Set the time high *)
LD FB_BLINK.OUT
ST Do00M00 (* Copy FB output to logic output *)
Type Library
7.13.2 BlinkValue, blink out value
FB eLLabUtyLib_C030
This function block executes a blinking output with the possibility to define the number of blinks.
Activating the Enable input, and defining the number of blinks in BlinkNr, the OutBit output blinks
with the number of blinks defined.
The number of blinks is defined in the tens and units. The value of tens is shown with a slow blink (1
sec), while the number of units is shown by blinking fast (250 ms). There is a pause of 3 sec between
blinking sequences.
Enable (BOOL) Enable function block. Activating it, the OutBit output is managed. Deactivating it, the output is reset.
BlinkNr (USINT) Defines the number of blink for the OutBit output. By defining time 0, the output is disabled.
OutBit (BOOL) Blinking output status.
Examples
Activating the Di00M00 digital input, the Do00M00 digital output blinks with 2 blinks slow (1 sec), 3 blinks fast (250 ms)
and a pause for 3 Sec.
Deactivating the Di00M00 digital input, the Do00M00 digital output resets immediately.
Defining variables
LD Di00M00
ST FBData.Enable (* Transfer the digital input to enable input *)
LD 23
ST FBData.BlinkNr (* Set the number of blink *)
LD FBData.OutBit
ST Do00M00 (* Copy FB output to logic output *)
ST example (Ptp114a100)
FBData(BlinkNr:=23); (* Call the BLINK function block *)
Type Library
7.13.3 ModbusMaster, modbus master
FB eLLabUtyLib_C030
This function performs the management of Modbus RTU, Ascii, TCP master protocol (Selectable by
Type). You can define the File I/O terminal on which to communicate. Setting the Enable, on the
terminal I/O is sent a frame to execute the modbus function defined in the FCode. Once the
command execution is finished the Done output is activated. If the command execution is
successful the Ok output will be set for a program loop. By disabling Enable the Done and Fault
output are reset, to run again the command the Enable input must re-enabled.
If FCode is a read function, the value of variables starting from Address for the number of variables
defined by Points, is read from the slave system and transferred into the variables addressed by
Buffer. The SpyOn input allows to spy the FB working.
If FCode is a write function, the value of variables addressed by Buffer for the number of variables
defined by Points, is written to the slave system starting from Address address.
On error executing command or command execution time bigger than the defined Timeout, the
Fault output will be activated for a program loop and the Errors counter increased.
Enable (BOOL) Command that enables Modbus command execution. To re-execute the command, disable and then
re-enable this input.
SpyOn (BOOL) Active allows to spy the FB working.
Code Description
16#01 Read coil status (Max 255 coils)
16#02 Read input status (Max 255 inputs)
16#03 Read holding registers (Max 32 registers)
16#04 Read input registers (Max 32 registers)
16#06 Preset single register
16#0F Force multiple coils (Max 255 coils)
16#10 Preset multiple registers (Max 32 registers)
Address (UINT) Address allocation of variables on slave system. According to the Modbus specifications, the
address sent in the frame is (Address-1) (Range from 16#0001 to 16#FFFF).
Points (USINT) Number of consecutive variables on which the command operates.
Buffer (@USINT) Address of buffer of read or written data.
Spy trigger
If SpyOn is active the SysSpyData function is executed this allows to spy the FB operations. There are various levels
of triggers.
TFlags Description
16#00000001 Tx: Modbus command frame sent.
16#00000002 Rx: Modbus answer frame received.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10007010 File value not defined.
10007050 Execution timeout.
10007060 Execution error.
10037080 Type definition error.
10007100 Function code defined in Function is not managed.
10007120 Wrong Points value.
10007200~2 Error transmitting the command frame.
10007500~7 Error receiving the answer frame (Wrong character, wrong length, won CRC).
Examples
Here an example of reading from a slave SlimLine. Cyclically is performed a read of 16 coils starting from address
16#01 of Modbus node 1. The value of the coils is transferred to the RxCoils array. After the reading will be activated
the Do01M00 logic output for a program loop.
Defining variables
Type Library
7.13.4 ModbusSlave, modbus slave
FB eLLabUtyLib_C030
SlimLine systems have got the Modbus slave protocol already implemented in the operating system,
so does not need a special function blocks in the user program. This block overrides the management
of the operating system and is used in special cases, where you can not use the management
implemented in the operating system. For example when you want to allow the access to your own
memory area different from DB100.
This function block performs the management of Modbus RTU, Ascii, TCP slave protocol (Selectable
by Type). It is possible to define the terminal I/O File on which to work.
It is possible to define the modbus Node and the frame address Offset. The received modbus
commands work on memory buffer whose address is defined in the Buffer and its size in bytes is
defined in Size.
In IFTime must be defined the interframe time of modbus command. This is the time that elapses
between the receiving frame and the next frame. On serial line this time coincides with the time of receiving 3
characters at defined baud rate.
On every received command, the Done output is activated for a program loop. If there is a command error, the Fault
output will be activated for a program loop and the Errors value will be increased.
Enable (BOOL) Enable function block.
File (FILEP) Stream returned from Sysfopen function.
Type (USINT) Modbus type selector. 0:RTU, 1:Ascii, 2:TCP
Node (USINT) Modbus node number (Range from 0 to 255).
Offset (UINT) Offset on received modbus frame address (Range from 16#0000 to 16#FFFF).
Buffer (@USINT) Address of buffer where the modbus commands read or write.
Size (UINT) Size in bytes of data buffer where the modbus commands read or write.
IFTime (UDINT) Time between frame (μS).
If you use the serial port, this time must be related to baud rate.
Supported command
The function block only supports a few commands provided by the Modbus protocol. The commands supported are:
Code Description
01 Read coil status (Max 250 coils)
02 Read input status ( Max 250 coils)
03 Read holding registers ( Max 125 registers)
04 Read input registers ( Max 125 registers)
05 Force single coil
06 Preset single register
08 Loopback diagnostic test
0F Force multiple coils ( Max 250 coils)
10 Preset multiple registers ( Max 125 registers)
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code. In case of modbus
command exception, the error code was reported without activate the Fault.
10038010 File value not defined.
10038050 Execution timeout.
10038060 Execution error.
10038080 Type definition error.
10038100~19 Received frame error (Frame length error).
10038150~1 Received frame error (Wrong CRC).
10038200~2 Error transmitting the answer frame.
10038501 Exception 01.Illegal function, received command non supported.
10038502 Exception 02. Illegal data address, received command with address or number of data out of range.
10038503 Exception 03. Illegal data value, received command with data out of range.
10038504 Exception 04.Failure in associated device, received command with errors.
Examples
Modbus RTU slave protocol is run on COM0. It uses the default serial settings 115200,e,8,1. The Modbus commands
can act on the DArray WORD array.
Defining variables
Type Library
7.13.5 OnOffCycle_v1, on/off cycle with random times
FB eLLabUtyLib_C030
This function block performs the timing of an on/off cycle with random On and Off time
defined between a minimum and maximum value. The maximun managed value is up to
1193 hours
Activating the Enable command, the Out output performs a blink on/off with a random time
between the minimum and maximum values defined. Disabling the input, the Out output is
deactivated.
The Delay variable return the actual delay time. The Time variable returns the time
countdown.
Enable (BOOL) Enable function block.
MinOffTime (UDINT) Minimum value for command off time (mS).
MaxOffTime (UDINT) Maximum value for command off time (mS).
MinOnTime (UDINT) Minimum value for command on time (mS).
MaxOnTime (UDINT) Maximum value for command on time (mS).
Out (BOOL) On/Off command status.
Delay (UDINT) Actual delay time used for temporization (mS).
Time (UDINT) Temporization countdown time (mS).
Example
It is executed the blinking of the Do00M00 output with random times between 2 and 4 seconds.
Defining variables
LD Di00M00
ST FBData.Enable (* Transfer the digital input to Enable input *)
LD 2000
ST FBData.MinOffTime (* Set the minimum off time *)
LD 4000
ST FBData.MaxOffTime (* Set the maximum off time *)
LD 2000
ST FBData.MinOnTime (* Set the minimum on time *)
LD 4000
ST FBData.MaxOnTime (* Set the maximum on time *)
LD FBData.Out
ST Do00M00 (* Copy the Out value to logic output *)
LD FBData.Delay
ST VarOut (* The Delay time is copied to variable *)
Type Library
7.13.6 PIDMng, PID management
FB eLLabUtyLib_C030
This function block executes the PID regulation. It is possible to enable individually the action to
use: (P)roportional (I)ntegrative, (D)erivative.
The Reverse command, allows to invert the sign of the Out output.
PIDEnable (BOOL) Enable PID control. By activating the input, the regulation is enabled. Disabling input resets the Out
output value.
IEnable (BOOL) Enable integrative regulation. By activating the input, the integrative regulation is enabled.
DEnable (BOOL) Enable derivative regulation. By activating the input, the derivative regulation is enabled.
Reverse (BOOL) By activating the input, the Out output value is inverted.
SetPoint (REAL) Set point. The value is expressed in the unity of measure of process to control.
PValue (REAL) Process variable. The value is expressed in the unity of measure of process to control.
PBand (REAL) Proportional band. This value defines the value of error beyond which the control is disabled and the
Out output is forced to ±100%. The value is expressed in the unity of measure of process to control.
ST (REAL) Scansion time. You need to set the time used to execute the integrative and derivative regulation if
enabled. The value is in mS.
KP (REAL) Proportional constant. Please note that with higher values, there is a more ready regulation with a
consequent increase of the overshot value. The value is a number.
IT (REAL) Integrative time. Please note that with higher values it is less fast to regain error. The value is in Sec.
DT (REAL) Derivative time. Please note that with higher values it is more fast to regain error. The value is in
Sec.
Enabled (BOOL) PID regulation enabled.
Error (BOOL) Execution error.
OUT (REAL) Correction value in output from PID. This value must be used to control the process. The value is
expressed in %. The range is between 0 and ±100%.
Error codes
If an error occurs, the Error output is activated and SysGetLastError can detect the error code.
10012050 Not defined value for ST.
Examples
In the example a temperature control is managed on a heater. A Pt100 temperature sensor is acquired and a PWM
output through Do00M00, is managed. The constants of the PID loop are allocated in backup so they are mantained at
power off. They are also accessible via Modbus.
Defining variables
Type Library
7.13.7 PWMOut, PWM output management
FB eLLabUtyLib_C030
Enable (BOOL) Enable PWM output management. Activating the input, the management is enabled. Deactivating the
input, the Out output is reset.
SET (REAL) PWM set value. It is expressed in %.
TCycle (REAL) PWM cycle time. Value is expressed in S.
TMin (REAL) Minimum Out command time. Value is expressed in S.
Out (BOOL) PWM output.
Examples
In the example is managed a PWM output defining a cycle time of 5 seconds with a minimum time of 0.5 seconds.
Setting the set point value and 50% and activating the Di00M00 input, the Do00M00 output will be activated for 2.5
seconds and deactivated for 2.5 seconds.
Defining variables
Type Library
7.13.8 SysDMXMng, DMX management
FB XTarget_07_0
This function block performs the management of the DMX protocol. This function block is protected
and require a code to unlock it (see functions and function blocks protection). It is possible to use
it freely in test mode for 15 min.
Activating the Start input, over the serial file identified by File, is sent a DMX frame that begins with
the value of Status and follows with the preset value of the devices defined by Devices. The preset
value of the various devices must be loaded into an array of data whose address is passed in
DataPtr. Keeping active the Start input, DMX frames are sent consecutively.
After sending the DMX command, the Done output will be activated for a program loop.
Start (BOOL) Send DMX command frame to serial port. It resets automatically when the frame is sent.
File (FILEP) Stream returned by Sysfopen function.
Status (USINT) Value of status byte sent as first byte of DMX frame, before the preset devices bytes.
Devices (UINT) Number of devices connected to DMX bus.
Delay (UINT) Wait time between DMX frames transmission (mSec)
DataPtr (@USINT) Pointer to array of DMS devices preset values.
Done (BOOL) Active for a program loop when a DMX frame is sent.
Fault (BOOL) Active if there is a management error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9979050 Function block allocation error.
9979060 Relocatable memory space full. You can not run the FB.
9979070 Function block version error.
9979085 Protected FB. The available time for demo mode is over.
9979200 DMX protocol not supported by device defined with File.
9979990 Not yet Implemented in the simulator.
Examples
Having to handle pointers to memory, it is preferable to use the function block within a ST program. The example
enables the DMX protocol on the serial port COM1. Five devices are managed with addresses from 1 to 5. The DMX
frame is continuously sent to the devices.
Activating the Di00M00 digital input, the value is set to 0 on all devices. Activating the Di01M00 digital input on the
device 1 is set a value 10, on the 2 the value 20, and so on until the fifth where the value is 50.
Defining variables
ST example
(* -------------------------------------------------------------------------- *)
(* SERIAL PORT OPEN *)
(* -------------------------------------------------------------------------- *)
(* Here the COM1 port is opened in read/write. *)
(* -------------------------------------------------------------------------- *)
(* COMMANDS ACTIVATION *)
(* -------------------------------------------------------------------------- *)
(* Commands activation on Di00M00 input. *)
DiPls[0](CLK:=Di00M00);
IF (DiPls[0].Q) THEN
DMXData[0]:=0; (* Preset device with address 1 *)
DMXData[1]:=0; (* Preset device with address 2 *)
DMXData[2]:=0; (* Preset device with address 3 *)
DMXData[3]:=0; (* Preset device with address 4 *)
DMXData[4]:=0; (* Preset device with address 5 *)
FBDMX.Start:=TRUE; (* Start *)
END_IF;
DiPls[1](CLK:=Di01M00);
IF (DiPls[1].Q) THEN
DMXData[0]:=10; (* Preset device with address 1 *)
DMXData[1]:=20; (* Preset device with address 2 *)
DMXData[2]:=30; (* Preset device with address 3 *)
DMXData[3]:=40; (* Preset device with address 4 *)
DMXData[4]:=50; (* Preset device with address 5 *)
FBDMX.Start:=TRUE; (* Start *)
END_IF;
(* -------------------------------------------------------------------------- *)
(* DMX PROTOCOL MANAGEMENT *)
(* -------------------------------------------------------------------------- *)
(* DMX protocol management. *)
(* [End of file] *)
Type Library
7.13.9 IOEncoder, incremental encoder over I/O
FB eLLabUtyLib_C030
This function block reads of an incremental encoder connected to the logic inputs. Simply place
the two digital input used as channel A and B of incremental encoder, to the two APhase and
BPhase input. The function block performs the quadrature signals, control of rotation direction
and manages the Quote value in output.
The quadrature signals performs the multiplication by 4 of encoder notches, so the Quote value at
the end of a complete revolution of the encoder is equal to the number of encoder notches
multiplied by 4.
Enable (BOOL) Enable the encoder counter management.
Reset (BOOL) Reset command. Activating it, the Quote value is reset.
APhase (BOOL) Encoder channel A.
BPhase (BOOL) Encoder channel B.
Enabled (BOOL) Encoder counter enabled.
Error (BOOL) Active for a program loop when there is an encoder acquisition error. It is activated if the frequency of
the encoder signals are bigger than the execution time of the function block.
Quote (UDINT) Encoder quote expressed in impulses. It is the number of notches/revolution multiplied by 4.
Examples
The example manages the acquisition of an incremental encoder connected to the inputs of the CPU module. Turning
the encoder for one revolution, the Quote value will be incremented if the rotation is clockwise (CW) or decremented if
the rotation is counterclockwise (CCW), of the number of notches per revolution multiplied by 4.
Defining variables
LD example
Type Library
7.13.10 GetISO1155Crc, calculate CRC according ISO1155
Function eLLabUtyLib_C030
This function calculates the CRC Cyclic Redundancy Check on a data area. This is
calculated in accordance with ISO 1155.
You must pass the address of the memory buffer Buffer and the number of bytes ByteNr on
which to perform the CRC calculation.
Buffer (@USINT) Address of memory buffer on which to execute the CRC calculation.
ByteNr (UINT) Number of bytes on which to execute the CRC calculation, starting from the address defined in Buffer.
Result (UINT) Calculated CRC value.
Example
It is calculated the CRC of a read request from the registry 1.8.1 from an electrical energy meter according to IEC
62056-2. The request frame is '<SOH>R1<STX>1.8.1()<ETX><CRC>'.
The CRC value returned in CRCValue is 16#5A (90 decimal).
Defining variables
ST example
(* ************************************************************************** *)
(* IEC1155 CRC CALCULATION *)
(* ************************************************************************** *)
(* Register read command '<SOH>R1<STX>1.8.1()<ETX><CRC>'. *)
Type Library
7.13.11 IODataExchange, exchange data by using logic I/O
FB eLLabUtyLib_C030
This function block allows data exchange between two systems, one master and one slave, using
a connection with I/O logic. They used two inputs and two outputs for each system. You can define
the number of bytes of data to be exchanged.
You must connect the OStrobe digital output of one system to the IStrobe digital input of other
system and the OData to the IData of the other.
Data transfer is bidirectional: data in the TxData buffer of a system are transferred into the RxData
buffer of the other system and vice versa, for the number of bytes defined by ByteNr.
Communication is verified by sending a CRC according to ISO 1155 standard.
At the end of each data transfer, the Done output is activated for a program loop. On its activation,
you must transfer the data to be transmitted in the transmission buffer, and read data from the
receive buffer.
In case of error in communication, the Fault output will be activated for a program loop, and the two systems
resynchronize to resume a new transmission.
Enable (BOOL) Communication enable.
IsMaster (BOOL) TRUE: Master mode, FALSE: Slave mode.
IStrobe (BOOL) Set to strobe digital input.
IData (BOOL) Set to data digital input.
RxData (UDINT) Buffer address of received data.
TxData (UDINT) Buffer address of data to send.
ByteNr (USINT) Number of bytes to exchange with other system (From 1 to 30).
TrigDelay (UINT) Time between out of OData and out of OStrobe (From 0 to 30 mS).
OStrobe (BOOL) Set to strobe digital output.
OData (BOOL) Set to data digital output.
Done (BOOL) Active for a program loop at the end of data exchange.
Fault (BOOL) Active for a program loop if data exchange error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10011080 Error defining ByteNr value.
10011082 Error defining TrigDelay value.
10011100~1 Timeout on waiting IStrobe signal activation.
10011110~1 Timeout on waiting IStrobe signal deactivation.
10011200~1 Wrong CRC of received data.
Examples
Using two systems and activating the master mode (Di01M00 active) on the first and the slave mode (Di01M00 off) on
the other, it is possible to exchange 4 bytes of memory between systems. The 4 bytes are allocated at address
MD100.0 of the first system, will be transferred to 4 bytes allocated to address MD100.16 of the other system.
After the transfer, the received data are transferred from memory MD100.0 to the RxData variable, while the TxData
variable is transferred in memory MD100.16.
Defining variables
LD example (Ptp121A000)
Type Library
7.13.12 Average, value average
FB eLLabUtyLib_C030
This function block performs the average on a value. The average action is defined by a
parameter Coefficient. An higher value for the parameter, increases the average action on the
Average output value.
Examples
It is executed an analog acquisition from the channel 0 of the module with address 0, in 0÷10 volts mode. The acquired
value is averaged and then transferred into the AnaValue variable.
Defining variables
Type Library
7.13.13 HIDClkDtaReader, HID RFID clock/data reader
FB eLLabUtyLib_C030
This function block executes the acquisition of an HID reader clock and data type. The FB must be
executed at least every 400 uSec, so we recommend to run the program the Fast task, defining the
execution time of the task through to 400 uS SysSetTaskLpTime function.
The function block can acquire RFID tags with code length up to 8 bytes, the code read is
transferred into the buffer addressed by CData, you must define the length of the code in
CDLength.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10039050 CDLength value error.
10039060 Execution error.
10039100~2 RFID tag read error.
Examples
It's managed to read an HID RFID clock and data reader connected to the CPU module. I remember that the program
must be executed at least every 400 uS, so it must be executed in the Fast task, setting it's execution time to 400 uS.
The code value read by the RFID tag is transferred CData array.
Defining variables
Type Library
7.13.14 Linearize, linearize a non linear value
Function eLLabUtyLib_C030
This function performs the linearization of a value. Must be provided to the function the
address definition array of the input value to be linearized VInReference, the address
definition array of the corresponding output value linearized VOutReference and the
number of values in the arrays ReferenceNr. It's important to define the data in the two
arrays in ascending order, starting from the smallest value.
The function searches in the VInReference array a value immediately higher than VIn
and interpolates between the value found and the previous one, calculating the output
value according to the two values in the same locations in the VOutReference.
VIn (REAL) Value to be linearized.
VInReference (@REAL) Pointer to the array that defines the input value to be linearized.
VOutReference (@REAL) Pointer to the array that defines the output value linearized.
ReferenceNr (USINT) Number of values in the linearization arrays.
(REAL) Linearized output value
Examples
It's performed an analog reading of a tank level, the tank has an irregular shape, through the function it's returned the
value of liters in the tank. The level value is averaged to have a more regular value.
1 volt corresponds to 1000 liters, 2 volts correspond to 4000 liters, 3 volts are 6000 liters.
Defining variables
Type Library
7.13.15 ValueScale, scales a value
Function eLLabUtyLib_C030
This function executes a value scaling. It's possible to define the minimum and maximum input
value to be scaled (ILow, IHigh) and the minimum and maximum output scaled value (OLow,
OHigh).
The use of this function is particularly suitable to converting values read from (4-20 mA) current
sensors in the corresponding measurement units detected by the sensor.
Examples
It's executed an analog acquisition of a temperature sensor with a 4-20 mA current output, the sensor has the output
value of 4 mA at -50 °C and 20 mA to 150 °C. Using the function the output current is directly converted in the
temperature value.
Defining variables
Type Library
7.13.16 GetPolynomialCRC, polynomial CRC calculation
Function eLLabUtyLib_C030
This function calculates the CRC Cyclic Redundancy Check on a data area. This is
calculated in accordance with CCITT.
You must pass the address of the memory buffer Buffer and the number of bytes Length on
which to perform the CRC calculation.
Data (@USINT) Address of memory buffer on which to execute the CRC calculation.
Length (UINT) Number of bytes on which to execute the CRC calculation, starting from the address defined in Data.
Result (WORD) Calculated CRC value.
Examples
The CRC calculation is performed on an array of data. Suppose you have an array of 8 bytes allocated in DB100 at
address 16 which contains the values 16#04, 16#3B, 16#1B, 16#00, 16#00, 16#00, 16#00, 16#00 , the calculated CRC
will be 16#5AF0.
Defining variables
Type Library
7.13.17 LRamp, linear ramp
FB eLLabUtyLib_C030
This function block executes a linear ramp on the input value. The output value Out follows the
input value In with slope values defined. The UPSlope value defines the ramp slope in raising, the
DWSlope value defines the ramp slope in fallingl. Disabling the function block the output is set to
zero.
The slope values are defined in units per second, for example with UPSlope set to 1 (1 unit per
second), assuming a step of 10 input In, we will have the output Out that reaches the value 10 in
10 seconds.
Enable (BOOL) FB enable.
In (REAL) Input value on which it is referred the output ramp.
UPSlope (REAL) Up slope ramp coefficent (Unit/Second)
DWSlope (REAL) Down slope ramp coefficent (Unit/Second)
Enable (BOOL) FB enabled.
Out (REAL) Output ramp value.
Examples
Is performed on a ramp value of Source with up slope of 1 and down slope of 2. Assuming a step of 10 in Source the
Destination will reaches the value on 10 seconds. Setting Source to 0 the Destination will reach the 0 on 5 seconds.
Defining variables
FBD example
Type Library
7.13.18 VaPotentiometer, voltage acquisition potentiometer
Function eLLabUtyLib_C030
This function calculates the ohmic value of a potentiometer acquiring the value of
output voltage from its cursor.
In PVoltage must be indicate the potentiometer supply voltage, Resistance is the
potentiometer resistance. Providing in AVoltage the voltage value readed from its
slide the function calculates the resistance value of the potentiometer to its current
location.
To compensate the reading error due to the input impedance of the voltage acquisition channel necessary to define it in
AImpedance.
PVoltage (REAL) Supply voltage of the potentiometer. The voltage applied to its extremes (V).
Resistance (REAL) Resistance value of the potentiometer (Ohm).
AVoltage (REAL) Voltage value acquired on the potentiometer slider (V).
AImpedance (REAL) Value of input impedance of the acquisition channel (Ohm).
(REAL)
Value of potentiometer resistance (Ohm).
Examples
AOxxv
AOxxi
AGnd
AIxx+
AIxx-
FIELD
PLC
It's acquired the ohmic value at the cursor position of a 5 kOhm potentiometer
powered with a voltage of 10 volts. The value is acquired through an analog input
P5
P4
module.
FIELD
PLC
RSeries
Rx
Defining variables
Type Library
7.13.19 ResistorValue, resistor value acquire
Function eLLabUtyLib_C030
This function calculates the ohmic value of a resistor acquiring the value of output
voltage from a resistor divider.
In PVoltage must be indicate the resistor divider supply voltage, RSeries is the Ohm
value of the series resistor. Providing in AVoltage the voltage value readed on the
resistor to be misured, the function calculates the resistance value.
To compensate the reading error due to the input impedance of the voltage acquisition
channel necessary to define it in AImpedance.
PVoltage (REAL) Supply voltage of the resistor divider (V)
RSeries (REAL) Series resistor value (Ohm).
AVoltage (REAL) Voltage value acquired on the resistor to be misured (V).
AImpedance (REAL) Value of input impedance of the acquisition channel (Ohm).
(REAL) Resistor value (Ohm).
Examples
AOxxv
AOxxi
AGnd
AIxx+
AIxx-
FIELD
PLC
It's calculated, the ohmic value of the resistor connected in a resistor divider with a
4,7KOhm. The divider is supplied with a voltage of 10 Volt. The value is acquired
P5
P4
through an analog input module. The acquired value is then filtered with a FB
FIELD
PLC
Average for having a stable value.
RSeries
Rx
Defining variables
Type Library
7.14.1 IEC62056_21Rd, IEC62056-21 protocol read
FB eLLabUtyLib_C030
This function block performs the management of read of registers from metering systems using
the protocol IEC62056-21. This function block is protected and require a code to unlock it (see
functions and function blocks protection). It is possible to use it freely in test mode for 30
min.
You must define SerialNr with the serial number of the counter (used as a key to reading) and
Register with the register address to read following the OBIS rules. If the reading is successful,
the Done output is activated and the variables MeterCode, Password and Value are set with
the data read from the counter.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10016010 File value not defined.
10016020 Protected FB. The available time for demo mode is over.
10016050 Execution timeout.
10016070 Error on case management.
10016100~1 Error receiving the counter type.
10016110~2 Error receiving the counter password.
10016120~2 Error receiving the counter parameter.
10016200 Overflow receiving string from counter.
Examples
There is a sample program Ptp122*000 that reads 3 records from an energy meter. Here we give an example for
reading a single register.
Upon activation of the Di00M00 digital input, it is executed the read of register 1.8.0 (Power in kW). If the reading is
successful, the Di00M00 digital output is activated for a program loop. The MeterCode, Password and Value variables
will be set with values read from the counter.
Defining variables
Type Library
7.15.1 ModemCore_v3, modem core management
FB eModemLib_E000
This function block manages a modem connected to the I/O device defined in File. This
function block is protected and require a code to unlock it (see functions and function
blocks protection). It is possible to use it freely in test mode for 30 min.
The FB manages the dialogue with the modem, it performs the initialization and monitors
the modem status, see if the modem is connected to the GSM network operator and
returns the operator and the Rssi signal level. If the modem is disconnected from the net, it
provides to its reconnection automatically. The FB returns a ModemID to be passed to the
associated FB (Example send SMS, receive SMS, etc..). The SpyOn input allows to spy
the FB working.
The Done output is activated if the modem is correctly initialized, while the Fault output is
activated for a program loop in case of error.
There is a PowerOn command to manage the modem's power. In this way, the FB can
power off and then on the modem if it finds a problem on it.
Upon receiving a telephone call, the CLIP of the caller is detected and returned in
CLIPNumber output. At the same time every ring of the phone, the CLIPRxd output is activated for a program loop. On
IPAddress it's returned the assigned IP on a GPRS connection.
Enable (BOOL) Enable function block. In this way the modem will be managed.
AutoHangUp (BOOL) Automatically hangs up the moden on a call receive, the FB returns the CLIP
SpyOn (BOOL) Active allows to spy the FB working.
File (FILEP) Stream returned by Sysfopen function.
APN (STING[32]) APN definition for the GPRS connection.
DNS (STING[16]) DNS server IP address.
Enabled (BOOL) Function block enabled.
Done (BOOL) Modem correctly initialized and working.
Fault (BOOL) Active for a program loop if management error.
PowerOn (BOOL) Command to use to power on and off modem.
CLIPRxd (BOOL) Active for a program loop every CLIP reception (Tipically every RING).
ModemID (UDINT) Modem ID to pass to linked FBs (Example ModemSMSSend, ModemSMSReceive, etc.).
CnStatus (USINT) Connection status.
0: Not registered.
1: Registered to home network.
2: Not registered, but ME is currently searching for a new operator.
3: Registration denied.
4: Unknown (not used).
5: Registered, roaming.
Operator (STRING[16]) Contain the string with the network operator.
Rssi (USINT) Value of Received signal strength indication.
CLIPNumber (STRING[16]) Contains the string with the received CLIP number.
IPAddress (STING[16]) IP address assigned by the network on a GPRS connection.
Spy trigger
If SpyOn is active the SysSpyData function is executed this allows to spy the FB operations. There are various levels
of triggers.
TFlags Description
16#00000001 'Rx' String received from modem
16#00000002 'R>' String received from modem is too long
16#00000004 'Tx' String transmitted to modem
16#00000010 'Mr' SMS received
16#01000000 '--' Modem operation labels
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
Code Description
10002010 File value not defined.
10002020 Protected FB. The available time for demo mode is over.
10002050 Execution timeout.
10002080 Management case mismatch.
10002100 Wrong Rx data from modem.
10002200~3 Error receiving CLIP.
10002300~3 Error in the power on sequence.
10002400~12 Error in the sequences for modem controlling.
10002350~7 Error receiving the SMS message.
Examples
In the example is managed a modem connected to the terminal I/O defined in the Fp variable. For definitions of
variables and a better understanding of the operation, see the examples below.
LD example
Type Library
7.15.2 ModemSMSReceive, receive a SMS message
FB eModemLib_E000
This function block performs the recepion of a SMS message. It connects to the ModemCore
function block using the ModemID input.
When a SMS message is received, the Done output will be activated for a program loop. On
the SMSText output is returned the message text received. On the CLIPNumber output of
ModemCore function block, is returned the phone number from which the message was
received. The text of the received message is present in output until the reception of another
message.
Enable (BOOL) Enables the reception of SMS messages.
ModemID (UDINT) Modem ID supplied as output from ModemCore.
Done (BOOL) Active for a program loop when a SMS is received.
Fault (BOOL) Active for a program loop if an error detected.
Text (STRING[160]) Received SMS message text.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10003010 ModemID not defined.
10003020 ModemID not defined.
Example
The example handles the reception of an SMS message from the ModemID modem. For definitions of variables and a
better understanding of the operation, see the examples below.
LD example (Ptp118b100, ReceiveSMSMessage)
Type Library
7.15.3 ModemSMSRxCmd_v1, receive a SMS command
FB eModemLib_E000
This function block performs the reception of a command via a SMS message. It connects to the
ModemCore function block using the ModemID input.
When a SMS message is received, the string defined in Command will be searched in the
received message. If found, the Done output will be activated for a program loop. In the
CLIPNumber output of the ModemCore FB, it is returned the phone number from which the
message was received.
Activating the Cin input, the search of Command string in the received string will be made without
considering the case (upper case / lower case) character.
Enable (BOOL) Enables the reception of SMS command.
ModemID (UDINT) Modem ID supplied as output from ModemCore.
CIn (BOOL) If active, the search of Command string, will be made without considering the case (upper
case/lower case) characters.
Command (@USINT) Pointer to the command text to execute.
Done (BOOL) Active for a program loop when a SMS containing the Command text is received.
Fault (BOOL) Active for a program loop if there is an error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10004010 ModemID not defined.
10004020 ModemID not defined.
Examples
The example handles the reception of an SMS message from the ModemID modem. For definitions of variables and a
better understanding of the operation, see the examples below.
LD example (Ptp118b100, ReceiveSMSCommand)
Type Library
7.15.4 ModemSMSSend_v2, send a SMS message
FB eModemLib_E000
This function block performs the sending of an SMS message. It connects to the ModemCore
function block using the ModemID input.
On the rising edge of Send input the send of message it's booked. As soon as possible, the text
message defined in Text will be sent to the number defined in Number. After sending, the Done
output will be enabled for a program loop.
The Tlgt parameter defines the number of characters of Text must be sent. If not defined or set
to “0” the entire Text string will be send.
Send (BOOL) On the rising edge, it force sending of message. Warning! The message will be sent as soon as
modem will be free to send.
ModemID (UDINT) Modem ID supplied as output from ModemCore.
Number (@USINT]) Pointer to phone number to which to send message.
TLgt (UDINT) Number of characters of Text must be sent. If “0” the entire Text string is sent.
Text (@USINT) Pointer to message text.
Done (BOOL) Active for a program loop when the message was sent.
Fault (BOOL) Active for a program loop if there is an error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10005010 ModemID not defined.
10005020 ModemID not defined.
10005080 Management case mismatch.
10005100~3 SMS send error.
Examples
The example handles the sending of an SMS message on modem defined by ModemID variable. For definitions of
variables and a better understanding of the operation, see the examples below.
LD example (Ptp118b100, SendSMSMessage)
Type Library
7.15.5 ModemPhoneCall_v1, executes a phone call
FB eModemLib_E000
This function block executes a call to the telephone number defined, It connects to the
ModemCore function block using the ModemID input.
On the rising edge of Call input the phone call it's booked. As soon as possible, the phone call to
the number defined in Number it's been done. If there are no problems the Done output will be
activated for a program loop.
Call (BOOL) On the rising edge, it force the phone call. Warning! The call will be executed as soon as
modem will be free.
ModemID (UDINT) Modem ID supplied as output from ModemCore.
Number (@USINT) Pointer to the phone number to call.
Time (UINT) Phone call delay (Sec).
Done (BOOL) Active for a program loop when the call is executed.
Fault (BOOL) Active for a program loop if there is an error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10037010 ModemID not defined.
10037020 ModemID not correct.
10037080 Management case mismatch.
10037100~3 Phone call sequencies error.
Example
In the example a call at the number defined it's executed. After 15 seconds the call is ended.
LD example (Ptp118b100, MakePhoneCall)
Type Library
7.15.6 ModemHTTPGet, executes a HTTP Get request
FB eModemLib_E000
This function block executes an HTTP request by inserting in line the GET parameters, It connects
to the ModemCore function block using the ModemID input.
On the rising edge of Send the modem connects to the HTPP Server on defined Port, and
requests the defined Page. The page is requested with GET parameters defined in the buffer
pointed to by GETPars. The page received from the server is transferred to the buffer pointed by
RxBuffer, the data received that exceed the size of the buffer RxSpace are discarded.
After the requested page has been received the Done output is activated for a loop, if the page is
not returned within the time defined in TimeOut execution terminates with an error.
Send (BOOL) On the rising edge, it force the page request. Warning! The request will be executed as soon
as modem will be free.
ModemID (UDINT) Modem ID supplied as output from ModemCore.
Server (@USINT) Pointer to HTTP server definition string.
Port (UINT) Port number on which connect.
Page (@USINT) Pointer to page definition string.
GETPars (@USINT) Pointer to GET parameters definition string (Up to 512 characters).
RxBuffer (@USINT) Pointer to page reception buffer (Up to 360 characters).
RXSpace (UINT) Page reception space definition.
TimeOut (UINT) Maximum time waiting page (mS).
Done (BOOL) Active for a program loop when the page is been received.
Fault (BOOL) Active for a program loop if there is an error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10042010 ModemID not defined.
10042020 ModemID not correct.
10042080 Management case mismatch.
10042100~8 HTTP page request sequencies error.
10042200 GET parameters string too long.
Examples
The typical use of this FB is to connect to an HTTP server where script pages (ASP, PHP, Python, etc.) are executed
requesting the page providing the GET parameters on-line to the call. The script of the page can perform operations
with data passed in line and return values as a result. Here is a simple example of a page using PHP script on the
server allows you to send an Email.
Defining variables
(* ---------------------------------------------------------------------- *)
(* INITIALIZATION *)
(* ---------------------------------------------------------------------- *)
(* General initializations. *)
IF (SysFirstLoop) THEN
ABf:=SysGetSerialMode(ADR(Sm), Mdm.File);
Sm.Baudrate:=115200; (* Baudrate *)
Sm.Parity:='N'; (* Parity *)
Sm.DataBits:=8; (* Data bits *)
Sm.StopBits:=1; (* Stop bits *)
Sm.DTRManagement:=DTR_OFF; (* DTR management *)
Sm.DTRComplement:=FALSE; (* DTR complement *)
Sm.EchoFlush:=TRUE; (* Flush the echo caracters *)
ABf:=SysSetSerialMode(ADR(Sm), Mdm.File);
(* ---------------------------------------------------------------------- *)
(* FBs MANAGEMENT *)
(* ---------------------------------------------------------------------- *)
(* Manage the modem core. *)
HTTP();
HTTP.Send:=FALSE;
(* ---------------------------------------------------------------------- *)
(* GET THE HTTP PAGE AND SEND THE EMAIL *)
(* ---------------------------------------------------------------------- *)
(* On digital input activation the HTTP page is requested. *)
IF (Pulse) THEN
ABf:=SysVarsnprintf(ADR(TxD), 128, 'To=%s', STRING_TYPE, ADR('[email protected]'));
ABf:=SysVarsnprintf(ADR(TxD)+LEN(TxD), 128-LEN(TxD), '$26Subject=%s', STRING_TYPE,
ADR('Subject'));
ABf:=SysVarsnprintf(ADR(TxD)+LEN(TxD), 128-LEN(TxD), '$26Text=%s', STRING_TYPE, ADR('Text'));
HTTP.Send:=TRUE;
END_IF;
END_IF;
IF (HTTP.Done) THEN
IF (FIND(RxD, 'Ok') = 0) THEN Result:=FALSE; ELSE Result:=TRUE; END_IF;
END_IF;
(* [End of file] *)
Let's explain how the program works, on rising edge of Di00M00 it's made the connection to the server
www.MyServer.com and it's requested the eMailSend.php page. In line to the call of the page are placed the GET fields
[email protected]&Subject=Subject&Text=Text. Note that the "&" character has been replaced by "$26".
The eMailSend.php page on server contains a PHP script like this:
<?php
$Headers="MIME-Version: 1.0\n";
$Headers.="Content-type: text/html; charset=iso-8859-1\n";
$Headers.="To: ".$_REQUEST['To']."\n";
$Headers.="From: \n";
mail($_REQUEST['To'], $_REQUEST['Subject'], $_REQUEST['Text'], $Headers);
echo "Ok";
exit();
?>
As you can see the script sends a mail by using the mail command whose fields are defined by the parameters set in
the GET request. The statement $_REQUEST['To'] contains the text defined in To=, $_REQUEST['Subject'] contains
the text defined in Subject=, and so on. As you can see it is possible to pass to the script all the values that you want.
The return value from the script, defined with the echo statement, will be transferred into the RxD buffer of our program
and then you can work on it with the string handling instructions.
Type Library
7.16.1 sOWireMng, One-Wire management
FB ePLC1WireLib_C000
This function block manages the Serial/One-Wire converter connected to the I/O device defined in
File. The FB handles the initialization and management of the converter.
The OnWork output is activated if Enable is active, the fault output is activated in case of
mismanagement and remains active until the error persists. Activity output is active during the One-
Wire bus activity. The FB returns a MngID to be passed to the connected FBs.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10008010 File value not defined.
10008200 Timeout on sending command string.
10008300~9 Error configuring converter.
10008400~1 Error verifying configuration.
10008500~2 Error in sequences for addressing the One-Wire device.
10008600 Answer error to reset pulse command.
10008601 One-Wire bus shortcircuit.
10008602 Error on One-Wire devices.
10008603 No One-Wire devices on the bus.
Type Library
7.16.2 sOWRdIdentifier, One-Wire read ROM identifier
FB ePLC1WireLib_C000
This function block reads the identification code of a One-Wire device. It connects to the
sOWireMng function block using the MngID input.
Activating the Enable command, is executed a read of the ID from the ROM device connected to the
One-Wire bus. Warning! You must have one only device connected to the bus. After reading the
code Done is set. If the reading is successful the Ok output is set for a program loop and the 8 bytes
code read is transferred into the array addressed by IDCode. Disabling Enable the Done and Fault
outputs are reset, to execute a new reading the Enable input must be reactivated.
Enable (BOOL) Enable function block.
MngID (UDINT) One-Wire ID supplied as output from OWireMng.
IDCode (@USINT) Pointer to array where to copy the read ROM ID. It must be at least 8 byte long.
Done (BOOL) Activated at the end of the ROM ID reading.
Ok (BOOL) Active for a program loop if ROM ID reading has been correctly done.
Fault (BOOL) Active for a program loop if there is an error.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10009010 MngID not defined.
10009020 MngID not defined.
10009030 IDCode not defined.
10009100 FB OWireMng, Serial/One-Wire converter management busy.
10009200~2 Error on One-Wire sequence reading ID.
Examples
Here's a simple example of a program for the management of iButton devices for
personal recognition. Inserting the TAG in the reader, the ROM identifier is read and
the value acquired is transferred to the ROMID array of 6 bytes.
Cyclically is performed an acquisition, if a TAG is inserted in the reader, the
TAGInserted flag is activated.
For simplicity, the program does not run any control to the ID read, but in an access
control system for example it is possible to identify the person and enable or not the
access.
Defining variables
Type Library
7.16.3 sOWRdTemperature, One-Wire read temperature
FB ePLC1WireLib_C000
This function block performs the acquisition of a One-Wire temperature sensor (Maxim
DS18B20). It connects to the sOWireMng function block using the MngID input.
By activating Enable command, is executed a read of temperature value from the device
connected to the One-Wire bus. Executed the acquisition the Done output become active,
if the value has been correctly read the Ok output is set for a program loop and the
acquired value is reported on Temperature output.
The Fault output is activated in case of error. Disabling Enable the Done and Fault outputs
are reset, to execute a new reading the Enable input must be reactivated.
If the One-Wire bus is connected to a single device, you can avoid setting IDCode or left it 0. However, if the One-Wire
bus have multiple parallel devices, in IDCode you must define the address of the array of 8 bytes contains the ROM ID
of the device you want to acquire.
Enable (BOOL) Enables function block.
MngID (UDINT) One-Wire ID supplied as output from OWireMng.
IDCode (@USINT) Pointer to array where to copy the read ROM ID. It must be at least 8 byte long.
Done (BOOL) Activated at the end of the temperature reading.
Ok (BOOL) Active for a program loop if temperature reading has been correctly done.
Fault (BOOL) Active for a program loop if there is an error.
Temperature (REAL) Acquired temperature value (°C). Range from -55 (°C) to +125 (°C). Precision ±0.5 (°C) from
-10 (°C) to +85 (°C). Resolution 0.0625 (°C).
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10010010 OWireID not defined.
10010020 OWireID not defined.
10010100 FB OWireMng, Serial/One-Wire converter management busy.
10010200~5 Error on read temperature sequence.
Examples
It is executed the read of temperature from a One-Wire device. Not being defined the IDCode, any device on the One-
Wire bus will be acquired. Warning! There must be a single device on the bus. If the execution is correct, the
Do00M00 output is activated and the acquired value is transferred into the Temperature variable.
Defining variables
Type Library
7.16.4 sOWRdHumidity, One-Wire read humidity
FB ePLC1WireLib_C000
This function block performs the acquisition of a One-Wire temperature and humidity
sensor (Maxim DS2438). It connects to the OWireMng function block using the MngID
input.
By activating Enable command, is executed a read of temperature and humidity values
from the device connected to the One-Wire bus. Executed the acquisition the Done output
become active, if the value has been correctly read the Ok output is set for a program loop
and the acquired values are reported on Temperature and Humidity outputs.
The Fault output is activated in case of error. Disabling Enable the Done and Fault outputs
are reset, to execute a new reading the Enable input must be reactivated.
If the One-Wire bus is connected to a single device, you can avoid setting IDCode or left it 0. However, if the One-Wire
bus have multiple parallel devices, in IDCode you must define the address of the array of 8 bytes contains the ROM ID
of the device you want to acquire.
Enable (BOOL) Enables function block.
MngID (UDINT) One-Wire ID supplied as output from OWireMng.
IDCode (@USINT) Pointer to array where to copy the read ROM ID. It must be at least 8 byte long.
Done (BOOL) Activated at the end of the temperature and humidity reading.
Ok (BOOL) Active for a program loop if temperature and humidity reading has been correctly done.
Fault (BOOL) Active for a program loop if there is an error.
Temperature (REAL) Acquired temperature value (°C). Range from -55 (°C) to +125 (°C). Precision ±0.5 (°C) from
-10 (°C) to +85 (°C). Resolution 0.03125 (°C).
Humidity (REAL) Acquired humidity value (RH%).
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10015010 OWireID not defined.
10015020 OWireID not defined.
10015100 FB OWireMng, Serial/One-Wire converter management busy.
10015200~3 Error on temperature conversion sequences.
10015300~8 Error acquiring the power supply voltage of sensor.
10015400~8 Errore acquiring the humidity sensor.
Examples
It is executed the read of temperature and humidity from a One-Wire device. Not being defined the IDCode, any device
on the One-Wire bus will be acquired. Warning! There must be a single device on the bus. If the execution is
correct, the Do00M00 output is activated and the acquired value is transferred into the Temperature and Humidity
variables.
Defining variables
Type Library
7.17.1 SysTCPServer, accepts TCP/IP connections
FB XTarget_12_0_0
Questa function block gestisce la comunicazione con protocollo TCP/IP in modalità server.
Occorre fornire l'indirizzo di un array di flussi dati streams al parametro FilesArr. Occorre
definire la porta TCP da porre in ascolto ed il numero di connessioni contemporanee
accettate.
Attivando il comando Enable il server TCP viene posto in ascolto sulla porta indicata, sulla
connessione di un client viene incrementato il numero di ConnPeers ed uno degli stream
definiti in FileArr viene valorizzato ed aperto. Sullo stream aperto è possibile utilizzare le
funzioni di TermIO per gestire la comunicazione.
Per modificare i parametri occorre disattivare e poi riabilitare il comando Enable.
Codici di errore
In caso di errore si attiva l'uscita Fault, con SysGetLastError è possibile rilevare il codice di errore.
Codice Descrizione
9942005 Blocco funzione non supportato.
9942050 Errore allocazione blocco funzione.
9942060 Terminato spazio memoria rilocabile, non è possibile eseguire l''FB.
9942070 Errore versione blocco funzione.
9942990 Non implementata nel simulatore.
Esempi
Nell'esempio è attivato un server TCP in ascolto sulla porta 1005. Il server accetta massimo 2 connessioni, su ogni
connessione viene eseguito l'echo del carattere ricevuto. Connettendosi in telnet alla porta 1005 inviando un carattere
se ne riceve l'echo.
Come si vede dall'esempio la gestione dell'echo è stata realizzata in due modi diversi per i due sockets in ascolto.
Definizione variabili
Type Library
7.17.2 SysTCPClient, opens a TCP/IP connection
FB XTarget_12_0_0
Questa function block gestisce la comunicazione con protocollo TCP/IP in modalità client.
Occorre definire l'indirizzo IP PeerIP e la porta TCP PeerPort del sistema server a cui ci
si vuole connettere. Attivando il comando Connect viene aperta la connessione con il
sistema server. Se la connessione và a buon fine viene attivato Connected e sull'uscita
File viene ritornato lo stream da utilizzarsi per lo scambio dati con il sistema server.
Se la connessione non è possibile viene generato Fault.
Codici di errore
In caso di errore si attiva l'uscita Fault, con SysGetLastError è possibile rilevare il codice di errore.
Codice Descrizione
9974005 Blocco funzione non supportato.
9974050 Errore allocazione blocco funzione.
9974060 Terminato spazio memoria rilocabile, non è possibile eseguire l''FB.
9974070 Errore versione blocco funzione.
9974990 Non implementata nel simulatore.
Esempi
Nell'esempio è attivata una connessione verso un server TCP in ascolto sulla porta 1000. Eseguita la connessione i
caratteri ricevuti dal server sono reinviati in echo.
Come server di prova è possibile utilizzare il programma Toolly scaricabile dal nostro sito.
Definizione variabili
Type Library
7.17.3 SysUDPServer, accepts UDP connections
FB XTarget_12_0
Questa function block gestisce la comunicazione con protocollo UDP in modalità server.
Occorre fornire l'indirizzo di un array di flussi dati streams al parametro FilesArr. Occorre
definire la porta UDP da porre in ascolto ed il numero di connessioni contemporanee
accettate.
Attivando il comando Enable il server UDP viene posto in ascolto sulla porta indicata,
sulla connessione di un client viene incrementato il numero di ConnPeers ed uno degli
stream definiti in FileArr viene valorizzato ed aperto. Sullo stream aperto è possibile
utilizzare le funzioni di TermIO per gestire la comunicazione.
Per modificare i parametri occorre disattivare e poi riabilitare il comando Enable.
Codici di errore
In caso di errore si attiva l'uscita Fault, con SysGetLastError è possibile rilevare il codice di errore.
Codice Descrizione
9945005 Blocco funzione non supportato.
9945050 Errore allocazione blocco funzione.
9945070 Errore versione blocco funzione.
9945990 Non implementata nel simulatore.
Esempi
Nell'esempio è attivato un server UDP in ascolto sulla porta 2000. Il server accetta massimo 2 connessioni, su ogni
connessione viene eseguito l'echo del carattere ricevuto. Connettendosi in telnet alla porta 1005 inviando un carattere
se ne riceve l'echo.
Come si vede dall'esempio la gestione dell'echo è stata realizzata in due modi diversi per i due sockets in ascolto.
Definizione variabili
Type Library
7.17.4 SysUDPClient, opens a UDP connection
FB XTarget_12_0
Questa function block gestisce la comunicazione con protocollo UDP in modalità client.
Occorre definire l'indirizzo IP PeerIP e la porta TCP PeerPort del sistema server a cui ci si
vuole connettere. Attivando il comando Connect viene aperta la connessione con il
sistema server. Se la connessione và a buon fine viene attivato Connected e sull'uscita
File viene ritornato lo stream da utilizzarsi per lo scambio dati con il sistema server.
Se la connessione non è possibile viene generato Fault.
Codici di errore
In caso di errore si attiva l'uscita Fault, con SysGetLastError è possibile rilevare il codice di errore.
Codice Descrizione
9943005 Blocco funzione non supportato.
9943050 Errore allocazione blocco funzione.
9943060 Terminato spazio memoria rilocabile, non è possibile eseguire l''FB.
9943070 Errore versione blocco funzione.
9943990 Non implementata nel simulatore.
Esempi
Nell'esempio è attivata una connessione verso un server TCP in ascolto sulla porta 1000. Eseguita la connessione i
caratteri ricevuti dal server sono reinviati in echo.
Come server di prova è possibile utilizzare il programma Toolly scaricabile dal nostro sito.
Definizione variabili
Type Library
7.17.5 SysGetIpInfos, returns IP infos
FB XTarget_12_0
Questo blocco funzione ritorna le informazioni della connessione. Passando al blocco funzione
un File di tipo TCP o UDP è possibile avere in uscite le informazioni relative.
Esempi
Nell'esempio sono visualizzate le informazioni di connessione al socket.
Definizione variabili
Type Library
7.17.6 SysIPReach, IP address is reachable
FB XTarget_07_0
This function block performs the check if an IP address is reachable. A Ping command is sent to the
system and if it's been answered Done is activated.
The Refresh variable returns the percentage of time elapsed since the last execution of the Ping
command. Reached the 50% of the time (Approximately 25 seconds) a new Ping command is sent.
Enable (BOOL) Enables function block. Activating it, a Ping command will be send every 25 Sec.
PeerIP (STRING[15]) IP address to reach.
Done (BOOL) Activated if IP address is reachable (Ping command is been answered).
Fault (BOOL) Active for a program loop if there is an error.
Refresh (USINT) Percentage of time from last Ping command.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
9974005 Function block not supported.
9974050 Function block allocation error.
9974060 Relocatable memory space full. You can not run the FB.
9974070 Function block version error.
9974100 FB executed not in the Back task.
9974110 Error on defined PeerIP address.
9974200 Error sending Ping request.
9974300 Error in Ping answer.
9974990 Not yet Implemented in the simulator.
Examples
The example checks whether the IP address 192.168.0.33 is reachable. In this case the Reached output is activated.
Defining variables
LD example
Type Library
7.17.7 UDPDataTxfer, UDP data transfer
FB eLLabNetworkLib_A000
This function block performs the transfer of a block of memory between two systems using
UDP over Ethernet connection. It is necessary to pass to File variable a data stream,
previously opened by the Sysfopen function, and the socket must have been set in
listening status using the SysSktListen function.
The PeerIP parameter indicates the IP address to which the data will be sent.The Port
parameter indicates the port used to transfer data (It must be the same for both systems).
The Timeout parameter defines the maximum time for data transfer. Delivery of data ends
with the receipt of an acknowledge from the other system. A cycle of sending data and
receiving acknowledge requires 2 loops of program. If after sending data, the Ack is not
received within a timeout period equal to Timeout/4, a new try is started and so on until the
end of the defined time. To guarantee at least 3 retries it is recommended to set as a
Timeout value of 10 times the maximum loop (you choose the higher from the two communication systems).
The data is sent automatically when a change in any of the bytes of the buffer is detected. To ensure control over the
connection between the two systems, each Timeout time the buffer data is sent.
If the two systems are communicating, the Done output is activated. RxDataOk will be activated for a program loop
every time you receive data from the other system, while TxDataSent is activated for a program loop at the end of the
transmission of data buffer to the other system.
Enable (BOOL) Enables function block.
File (FILEP) Stream returned by Sysfopen function.
PeerIP (STRING[15]) IP address of server to which to send data.
Port (UINT]) Port used to transfer data (It must be the same for both systems).
RxDBuffer (@USINT]) Pointer to buffer where to transfer the received data.
TxDBuffer (@USINT]) Pointer to buffer containing data to send.
ByteNr (UDINT]) Number of exchanged bytes.
Timeout (UINT]) Maximum time to transfer data (mS).
Done (BOOL) Activated when both systems are in communication.
Fault (BOOL) Active for a program loop if there is an error.
RxDataOk (BOOL) Active for a program loop when data are received from other system.
TxDataSent (BOOL) Active for a program loop at the end of data transmission to other system.
Errors (UINT]) Number of errors. Incremented every new error occurs. When it reaches the maximum value,
it restart from 0.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10014050 File value not defined.
10014100 Relocatable memory space full. You can not run the FB.
10014200~2 Error receiving data frame.
10014300~2 Error receiving acknowledge.
10014400 Received an unknow command.
10014500~1 Error on transmission sequences.
10014600 Timeout on sending data.
Examples
In the example, a block of 16 bytes of memory is echanged to the system with IP 192.168.0.126.
Defining variables
Type Library
7.17.8 DataStreamExch, exchanges data between two I/O streams
Function eLLabNetworkLib_A000
This function block performs data exchange between two I/O streams. By defining a stream as
a TCP socket and the other as serial port, it is possible to realize a Ethernet/Serial converter.
In FpA and FpB must indicate the file pointer in output from the Sysfopen function opening the
I/O stream. The FB receives data from a stream and stores them in a buffers of DBSize size,
when non data is received for a DDelay sends them to the other stream.
If are received more data than the defined size of the buffer, the data is immediately sent on the
other stream and an error is generated.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10048100 Data buffer allocation error.
10048200 Data buffer full on data reception forom stream (A).
10048250 Data buffer full on data reception forom stream (B).
Examples
A simple Ethernet/Serial converter, accepts TCP connection on port 1000 and uses the COM0 serial port.
Defining variables
IF (SysFirstLoop) THEN
(* ---------------------------------------------------------------------- *)
(* GESTIONE SCAMBIO DATI DA TCP E RTU *)
(* ---------------------------------------------------------------------- *)
(* Gestione scambio dati tra Modbus TCP e Modbus RTU. *)
(* [End of file] *)
Type Library
7.17.9 ModbusTCPGateway, modbus TCP gateway
FB eLLabNetworkLib_A000
This function block operates as Modbus gateway between Modbus TCP connection and
a serial Modbus RTU. In FpTCP must pass the I/O stream from which arrive the Modbus
TCP requests. In FpRTU must pass the I/O stream to which are sent the converted to
Modbus RTU requests.
In IFTime must be defined the pause time of receiving characters from the serial port
(Modbus RTU). Timeout defines the maximum execution time of a command Modbus
TCP (From when the command is received to when after conversion the Modbus RTU
response is returned).
The SpyOn if active allows to spy the FB operation. In case of execution error or
execution time greather than the time set in Timeout, is activated for a program loop the
Fault output.
Enable (BOOL) Command that enables the FB.
SpyOn (BOOL) Active allows to spy the FB working.
FpTCP (FILEP) Stream returned from Sysfopen function.
FpRTU (FILEP) Stream returned from Sysfopen function.
IFTime (UDINT) Time between frame (μS), it must be related to baud rate.
Timeout (UINT) Maximum command execution time expressed in mS. If the command does not end in the defined
time, the command is aborted and the Fault output is activated
Enabled (BOOL) FB enabled.
Fault (BOOL) Active for a program loop if execution error.
Spy trigger
If SpyOn is active the SysSpyData function is executed this allows to spy the FB operations. There are various levels
of triggers.
TFlags Descrizione
16#00000001 Tx: Modbus RTU command frame sent.
16#00000002 Rx: Modbus RTU answer frame received.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code..
10053050 Execution timeout
10053100~1 Modbus TCP frame management error.
10053200~1 Modbus RTU frame management error.
Examples
Simple Modbus TCP/RTU gateway, accepts TCP connection on port 2000 and uses the serial port COM2.
Defining variables
(* ---------------------------------------------------------------------- *)
(* GESTIONE SCAMBIO DATI DA TCP E RTU *)
(* ---------------------------------------------------------------------- *)
(* Gestione scambio dati tra Modbus TCP e Modbus RTU. *)
(* [End of file] *)
Type Library
7.17.10 SNTPRequest, sends a SNTP request
FB eLLabNetworkLib_A000
This function block reads from a time server the UTC time. By activating the Query command
a request is sent to the server passed in NTPServer.
The FB queries the server and if answered correctly UTCTime returns the value of time in
UTC Epoch. In Offset is returned in the difference between the UTC value returned and the
NTP clock reference.
At the end of execution the Done output is activated, to make a new time reading must be
deactivate and then reactivate the Query input. In RTDelay is returned the round trip delay,
the time required to transmit the request and receive the response from the NTP server.
Query (BOOL) Request activation command.
SpyOn (BOOL) Active allows to spy the FB working.
NTPServer (STRING[15]) NTP server IP address definition.
Done (BOOL) Active at the end of execution, is active even in case of Fault.
Ok (BOOL) Active for a program loop if query correctly executed.
Fault (BOOL) Active for a program loop if execution error.
RTDelay (REAL) Round trip delay, time required to transmit the request and receive the response from the NTP
server (mS).
UTCTime (UDINT) Date/Time in UTC expressed in Epoch time.
Offset (REAL]) Difference between the UTC value returned and NTP reference clock (mS).
Spy trigger
If SpyOn is active the SysSpyData function is executed this allows to spy the FB operations. There are various levels
of triggers.
TFlags Description
16#00000001 '--' NTP request informations.
16#00000002 '--' Reports of all operations performed.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10052010 FB not executed in the background task.
10052010 No more UDP sockets available.
10052100 Error on pinging NTP server.
10052110 Error socket in listening.
10052120 Error receiving data from the socket.
10014200~3 Error in the management sequences.
Examples
It's required the time from the ntp1.inrim.it (193 204 114 232) server.
Defining variables
LD example
Type Library
7.17.11 DNSRequest, sends a DNS request
FB eLLabNetworkLib_A000
Questo blocco funzione invia una richiesta DNS. Indicando in DNSServerIP l'indirizzo
IP di un server DNS (Esempio quello di Google 8.8.8.8) è possibile effettuare la
richiesta di risoluzione di un dominio. Viene ritornato l'indirizzo IP ed il tempo di vita
dell'URL.
Attivando l'ingresso Enable viene effettuata la richiesta di risoluzione dell'URL al
server DNS. Se il server risolve l'URL viene attivata l'uscita Done e su DomainIP
viene ritornato l'IP relativo.
Se Enable rimane attivo il FB controlla in tempo di vita della voce DNS ed esegue il
riaggiornamento automatico dell'indirizzo IP. L'ingresso SpyOn se attivo permette di
spiare il funzionamento del FB.
Enable (BOOL) Comando abilitazione esecuzione. Per rieseguire il comando disabilitare e poi riabilitare
questo ingresso.
SpyOn (BOOL) Se attivo permette di spiare il funzionamento della FB.
DNSServerIP (STRING[15]) Stringa di definizione IP server DNS.
Domain (@USINT) Indirizzo stringa definizione URL di cui si desidera risolvere l'IP.
QType (UINT) Tipo di query.
Codice Descrizione
16#0001 A record (host addresses).
16#0002 Name servers (NS) records (Not managed).
16#000F Mail server (MX).
Done (BOOL) Si attiva al termine della esecuzione comando.
Fault (BOOL) Attivo per un loop se errore esecuzione comando.
Domain (STRING[15]) Stringa di definizione IP trovato.
RTime (UDINT) Tempo riferimento per controllo sul tempo di vita richiesta (uS).
TTL (UDINT) Tempo di vita richiesta (S).
Trigger di spy
Se SpyOn attivo viene eseguita la funzione SysSpyData che permette di spiare il funzionamento della FB. Sono
previsti vari livelli di triggers.
TFlags Descrizione
16#00000001 Tx: Invio richiesta DNS.
16#00000002 Rx: Ricezione risposta DNS.
16#10000000 Lg: Messaggio di log.
16#20000000 Wr: Messaggio di warning.
16#40000000 Er: Messaggio di errore.
Codici di errore
In caso di errore si attiva l'uscita Fault, con SysGetLastError è possibile rilevare il codice di errore.
Codice Descrizione
10055010 FB eseguita in una task diversa dalla task di background.
10055020 File non corretto.
10055100 Errore lunghezza nome dominio da risolvere.
10055200 Timeout risposta da server.
10055210~5 Formato pacchetto ricevuto non corretto.
10055800 Errore esecuzione.
Esempi
Nell'esempio viene richiesto l'indirizzo IP di “elsist.it” al server DNS di Google.
Definizione variabili
Esempio LD
Type Library
7.17.12 HTTPProtocol, HTTP protocol management
FB eLLabNetworkLib_A000
Questo blocco funzione esegue la richiesta di una pagina web con il protocollo HTTP. Su
fronte attivazione ingresso Enable viene inviata la richiesta HTTP sullo stream di I/O
definito in File. Ricevuta la pagina si attiva per un loop di programma l'uscita Ok.
Nel parametro Host occorre definire il nome host del server HTTP, mentre in Page occorre
definire la pagina da richiedere. La pagina viene richiesta con i parametri definiti nel buffer
Request. La pagina richiesta viene ritornata nel buffer definito in Pbuffer. In PLength è
ritornata la lunghezza della pagina ricevuta.
In caso di errore esecuzione o tempo di esecuzione comando superiore al tempo definito in
Timeout, viene attivata per un loop di programma l'uscita Fault.
L'uscita Done si attiva al termine della esecuzione della richiesta e su errore, per acquisire
nuovamente la pagina occorre disabilitare e poi riabilitare l'ingresso Enable.
Enable (BOOL) Comando attivazione richiesta pagina.
SpyOn (BOOL) Se attivo permette di spiare il funzionamento della FB.
File (FILEP) Flusso dati stream ritornato dalla funzione Sysfopen.
Host (STRING[128]) Stringa di definizione Host name.
Page (STRING[128]) Stringa di definizione pagina web richiesta.
Request (@USINT) Indirizzo buffer dati da inviare con la richiesta.
PBuffer (@USINT) Indirizzo buffer pagina ricevuta.
PBLength (UDINT) Dimensione buffer di pagina.
Timeout (UINT) Timeout esecuzione richiesta pagina (mS).
Done (BOOL) Attivo a fine esecuzione, si attiva anche in caso di Fault.
Ok (BOOL) Attivo per un loop di programma su ricezione pagina.
Fault (BOOL) Attivo per un loop di programma se errore gestione.
HTTPStatus (STRING[64]) Status risposta HTTP ricevuta.
PLength (UINT) Dimensione pagina ricevuta.
PLTime (REAL) Tempo impiegato per caricamento pagina (S).
Codici di errore
In caso di errore si attiva l'uscita Fault, con SysGetLastError è possibile rilevare il codice di errore.
Codice Descrizione
10054010 File non definito
10054020 FB eseguita in una task diversa dalla task di background.
10054100 Timeout richiesta pagina.
10054200 Campo Request troppo lungo.
10054300~1 Errore ricezione lunghezza pagina.
10054300 Errore ricezione stringa risposta da server.
Esempi
Nell'esempio viene eseguita la richiesta della pagina www.slimline.altervista.org/Tutorials/HTTPProtocol.php. Sono
passati alla pagina 2 parametri Dividend e Divisor, la pagina è postata su Altervista ed al suo interno un semplice
script PHP esegue la divisione tra i due valori passati e ritorna il risultato.
Se da un browser si indirizza la pagina www.slimline.altervista.org/Tutorials/HTTPProtocol.php?
Dividend=500&Divisor=10 otterremo come ritorno la scritta “The result is: 50” che è esattamente quello che si trova in
PContent.
Definizione variabili
Esempio LD
Ma per capire come l'esempio funzioni occorre fare un preambolo. La versione attuale del sistema operativo dei sistemi
SlimLine non permette di utilizzare i socket TCP in modalità client. Per potersi connettere al server di Altervista
nell'esempio ho utilizzato un convertitore Ethernet/Seriale (Nel mio caso un ATC-3000) configurato come client TCP.
La porta seriale è settata con i parametri standard di default dei sistemi SlimLine 115200, e, 8, 1.
Nella connessione TCP/IP ho definito come porta remota la porta HTTP (80) e come remote host il DNS del sito.
Collegando la porta seriale COM0 del sistema SlimLine alla porta seriale del convertitore ATC-3000 i dati inviati in
uscita dalla FB HTTPGetPage raggiungono il server di Altervista che gestisce la richiesta ritornando la pagina richiesta.
Il contenuto della pagina ricevuto dall'ATC-3000 sono passati via porta seriale allo SlimLine che li interpreta.
Type Library
7.18.1 STESnmpAcq, STE termometer acquisition over SNMP
FB eHwGSpLib_B000
This function block manages the acquisition of the values of the two temperature probes
connected to the IP STE thermometer. The connection between the thermometer and the
SlimLine is made over an ethernet network using SNMP protocol.
You must pass to FB the data stream indicated by the File parameter, previously opened by the
Sysfopen function as a socket, and the socket must have been set in listening status using the
SysSktListen function.
On the rising edge of the Acquire command, a SNMP read is made from the STE thermometer
identified by PeerIP address and port defined by PeerPort (By default, the SNMP port is 161). If
the Acquire command stay active, the read is done cyclically.
The Done output is activated for a program loop at the end of the acquisition of the two temperature values.
Enable (BOOL) Enables function block.
Acquire (BOOL) On the rising edge of command, start the acquisition of temperature from STE thermometer.
On the rising edge of command, the acquisizione termometro STE. If command stay active,
the read is done cyclically.
File (FILEP) Stream returned by Sysfopen function.
PeerIP (STRING[15]) IP address of IP thermometer.
PeerPort (UINT]) Port used for connection (By default, the SNMP port is 161).
Done (BOOL) Active for a program loop at the end of read.
Fault (BOOL) Active for a program loop if there is an error.
Sensor1 (REAL) Temperature value from sensor 1 (°C).
Sensor2 (REAL) Temperature value from sensor 2 (°C).
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10013010 File value not defined.
10013050 Execution timeout.
10013060 Error on read management.
10013100 Error controlling the IP address of STE device.
10013120 Errore receiving data from STE device.
10013200~1 Error reading sensor 1.
10013300~1 Error reading sensor 2.
Examples
In the example, every second is managed the acquisition of the two values of temperature from a STE thermometer.
The value of temperature in Celsius degrees is returned in the variables Temperature[0] and Temperature[1]. The
Do00M00 logic output is activated at the first acquisition, while the Do01M00 logic output is activated when an error
detected.
Defining variables
LD example
Type Library
7.18.2 sHWgSProtocol, HW group serial protocol
FB eHwGSpLib_B000
This function block handles the reading of the HW group devices by using the RS485 ascii
protocol. You must pass the pointer of the data stream of type serial port indicated by the File
parameter previously opened by the Sysfopen function.
Activating the Enable input is read the value from the addressed device connected to the serial
port defined, terminated the execution the Done output is activated. If the command is successful
the Ok output is set, otherwise the Fault output is set.
To repeat the command it's necessary to deactivate and then activate the Enable input, function
block has been designed to allow the cascade connection. In practice it is possible to connect to
an the Done output of one FB to the Enable input of another FB and so on.
Enable (BOOL) Enables function block.
File (FILEP) Stream returned by Sysfopen function.
Address (STRING[1]) String that defines the device address.
Done (BOOL) Active for a program loop at the end of data read.
Ok (BOOL) Active on value read.
Fault (BOOL) Active on error.
Errors (UDINT) Number of errors. Incremented every new error occurs. When it reaches the maximum value,
it restart from 0.
TxFrame (STRING[8]) Contain the frame sent to device. It can be used for debug purpose.
RxFrame (STRING[16]) Contain the frame received from device. It can be used for debug purpose.
Value (REAL) Acquired value.
Error codes
If an error occurs, the Fault output is activated, the Errors value is incremented and SysGetLastError can detect the
error code.
10032010 File value not defined.
10032050 Execution timeout.
10032060 Error on read management.
10032100 Fb used on fast or slow task.
10013200~1 Error in the communication protocol management.
10032300 Error on value reading.
Examples
This example is the acquisition of the temperature and humidity from a HTemp device.
Defining variables
Type Library
7.19.1 NMEASInterface, NMEA system interface
FB eNMEALib_B000
This function block handles the interface to a device that sends NMEA sentences. This device
must be connected to the I/O terminal defined in File. This function block is protected and
require a code to unlock it (see functions and function blocks protection). It is possible to
use it freely in test mode for 30 min.
FB receives NMEA sentences from the device, it checks the code by comparing it with the string
defined in the DID and see if the sentence received is correct (Check the CRC). The Done
output is activated for a program loop at each receiving NMEA sentence correct.
FB returns a NMEAID to be passed to the associated FB (FB NMEA sentences management). The output shows the
RxString string received from the device. In this way you can show it, allowing you to view any errors.
Enable (BOOL) Enables function block.
File (FILEP) Stream returned by Sysfopen function.
DID (STRING[2]) String that define the device prefix.
Done (BOOL) Active for a program loop when a correct sentence is received.
Fault (BOOL) Active for a program loop if there is an error.
NMEAID (UDINT) NMEA ID to pass to the linked FBs.
RxString (STRING[82]) Contain the string received from device. It can be used for debug purpose.
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10017010 File value not defined.
10017020 Protected FB. The available time for demo mode is over.
10017050 Execution timeout.
10017070 Management case error.
10017100~4 Error receiving NMEA sentence.
Type Library
7.19.2 GLLSentence, Geographic Position sentence
FB eNMEALib_B000
This function block performs the receipt of the GLL Geographic Position sentence. It
connects to the NMEASInterface function block using the NMEAID variable.
The GLL sentence contains the information of latitude, longitude, time and fix. Example of
sentence $IIGLL,4419.0173,N,00829.6653,E,084550.00,A,2*09.
The FB checks the correctness of sentence fields and extracts the information of latitude,
longitude and time. The Done output is activated for a program loop at each correctly
received GLL sentence.
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10018010 NMEAID not defined.
10018020 NMEAID not correct.
10018100~2 Latitude value error.
10018200~2 Longitude value error.
10018300~2 UTC hour value error.
Examples
It is available a sample program Ptp123*000 that manages the interface to a navigation system with the interpretation of
some NMEA sentences.
The example is managed the receive of a GLL sentence.
Defining variables
LD example
Type Library
7.19.3 MWVSentence, Wind Speed and Angle sentence
FB eNMEALib_B000
This function block performs the receipt of the sentence MWV wind speed and angle. It connects
to the NMEASInterface function block using the NMEAID variable.
The MWV sentence contains the information of speed and wind direction. An example sentence
is $IIMWV,120.09,R,4.53,N,A*35.
The FB checks the correctness of the sentence fields and extracts the information of speed and
direction. The Done output is activated for a program loop at each correctly received MWV
sentence.
Enable (BOOL) Enables function block.
NMEAID (UDINT) NMEA ID supplied as output from NMEASInterface.
Done (BOOL) Active for a program loop if a correct MWV sentence received.
Fault (BOOL) Active for a program loop if there is an error.
WSpeed (REAL) Wind speed value (Nodes).
WPAngle (REAL) Polar angle value (Relative) of wind direction.
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10020010 NMEAID not defined.
10020020 NMEAID not correct.
10020100 Wind speed value error.
Type Library
7.20.1 AuroraDSPMeasure, Aurora measure request to DSP
FB ePowerOneLib_B000
This function block reads the measurements from the DSP of a Power One Aurora inverter,
connected to the I/O device defined in File. This function block is protected and require a code to
unlock it (see functions and function blocks protection). It is possible to use it freely in test
mode for 30 min. It is used the GetPolynomialCRC function for CRC calculation of data frame to
and from the inverter.
The connection to the inverters is RS485 multidrop. In Address you must define the inverter
address with which you want to talk. In Measure you must specify the measure code of what you
want to read (See measure codes).
By activating the Start input, the chosen measure is read. After the reading, the Done output will be activated for a
program loop. If an error occurs, the Fault output will be activated for a program loop and the Errors value will be
incremented.
Enable (BOOL) Enables function block.
Start (BOOL) Command to read the measure.
File (FILEP) Stream returned by Sysfopen function.
Address (USINT) Inverter address (Range from 0 to 255).
Measure (USINT) Type of measure to read from inverter (See measure codes).
Done (BOOL) Active for a program loop at the end of command execution.
Fault (BOOL) Active for a program loop if there is an error.
Value (REAL) Measure value read from inverter (It is in the relative measure unity).
Errors (UDINT) Number of errors. Incremented every new error occurs. When it reaches the maximum value, it
restart from 0.
Measure codes
In the Measure variable, you must define the Code of the measure to do from the inverter according to the table below.
Code Description Um
1 Grid Voltage (For three-phases systems is the mean) V
2 Grid Current (For three-phases systems is the mean) A
3 Grid Power (For three-phases systems is the mean) W
4 Frequency (For three-phases systems is the mean) Hz
5 Vbulk (For Inverter with more Bulk is the sum) V
6 Ileak (Dc/Dc) A
7 Ileak (Inverter) A
21 Inverter Temperature °C
22 Booster Temperature °C
23 Input 1 Voltage (Input Voltage for single channel module) V
25 Input 1 Current (Input Current for single channel module) A
26 Input 2 Voltage (Input Voltage for single channel module) V
27 Input 2 Current (Input Current for single channel module) A
28 Grid Voltage (Dc/Dc) V
29 Grid Frequency (Dc/Dc) Hz
Code Description Um
30 Isolation Resistance (Riso)
31 Vbulk (Dc/Dc) V
32 Average Grid Voltage (VgridAvg) V
33 VbulkMid V
34 Power Peak W
35 Power Peak Today W
36 Grid Voltage neutral V
37 Wind Generator Frequency Hz
38 Grid Voltage neutral-phase V
39 Grid Current phase r A
40 Grid Current phase s A
41 Grid Current phase t A
42 Frequency phase r Hz
43 Frequency phase s Hz
44 Frequency phase t Hz
45 Vbulk + V
46 Vbulk - V
47 Supervisor Temperature °C
48 Alim. Temperature °C
49 Heat Sink Temperature °C
61 Grid Voltage phase r V
62 Grid Voltage phase s V
63 Grid Voltage phase t V
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10030010 File value not defined.
10030020 Protected FB. The available time for demo mode is over.
10030050 Execution timeout.
10030070 Management case error.
10030100 CRC error on answer from Aurora inverter.
10030200 Error receiving the “Transmission state” from Aurora inverter.
10030251 Error from Aurora inverter: “Command is not implemented”.
10030252 Error from Aurora inverter: “Variable does not exist”.
10030253 Error from Aurora inverter: “Variable value is out of range”.
10030254 Error from Aurora inverter: “EEprom not accessible”.
10030255 Error from Aurora inverter: “Not Toggled Service Mode”.
10030256 Error from Aurora inverter: “Can not send the command to internal micro”.
10030257 Error from Aurora inverter: “Command not Executed”.
10030258 Error from Aurora inverter: “The variable is not available, retry”.
Examples
It is executed the read of the measure 21 (Inverter Temperature) from inverter with address 4. The return value is
transferred to the Value variable. By default the serial port must be set to 19200,n,8,1.
Defining variables
LD example
Type Library
7.20.2 AuroraCEnergy, Aurora cumulated energy reading
FB ePowerOneLib_B000
This function block reads the generated energy by a Power One Aurora inverter, connected to
the I/O device defined in File. This function block is protected and require a code to unlock it
(see functions and function blocks protection). It is possible to use it freely in test mode for 30
min. It is used the GetPolynomialCRC function for CRC calculation of data frame to and from
the inverter.
The connection to the inverters is RS485 multidrop. In Address you must define the inverter
address with which you want to talk. In Parameter you must specify the parameter to read (See
parameter codes).
By activating the Start input, the chosen parameter is read. After the reading, the Done output will be activated for a
program loop. If an error occurs, the Fault output will be activated for a program loop and the Errors value will be
incremented.
Enable (BOOL) Enables function block.
Start (BOOL) Command to read the parameter.
File (FILEP) Stream returned by Sysfopen function.
Address (USINT) Inverter address (Range from 0 to 255).
Parameter (USINT) Parameter code to read (See parameter codes).
Done (BOOL) Active for a program loop at the end of command execution.
Fault (BOOL) Active for a program loop if there is an error.
Value (UDINT) Parameter value read from inverter (It is in the relative measure unity).
Errors (UDINT) Number of errors. Incremented every new error occurs. When it reaches the maximum value, it
restart from 0.
Parameter codes
In the Parameter variable, you must define the Code of the parameter to read from the inverter according to the table
below.
Code Description Um
0 Daily energy Kw
1 Weekly Energy Kw
3 Month Energy (Energy from the first day of current calendar month) Kw
4 Year Energy (Energy from the first day of current calendar year) Kw
5 Total Energy (Total lifetime) Kw
6 Partial Energy (Cumulated since reset) Kw
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10031010 File value not defined.
10031020 Protected FB. The available time for demo mode is over.
10031050 Execution timeout.
10031060 Wrong parameter code.
10031070 Management case error.
10031100 CRC error on answer from Aurora inverter.
Example
It is executed the read of the total of the energy produced by the inverter with address 1. The return value is transferred
to the Value variable. By default the serial port must be set to 19200,n,8,1.
Defining variables
LD example
Facility codes
0 Kernel messages
1 User-level messages
2 Mail system
3 System daemons
4 Security/authorization messages
5 Messages generated internally by syslogd
6 Line printer subsystem
7 Network news subsystem
8 UUCP subsystem
9 Clock daemon
10 Security/authorization messages
11 FTP daemon
12 NTP subsystem
Severity codes
0 Emergencies Sistema inutilizzabile
1 Alerts Richiede intervento immediato
2 Critical Condizioni critiche
3 Errors Condizione d'errore
4 Warnings Condizioni di warning
5 Notifications Condizioni di anomalia non critici (bugs)
6 Informational Messaggi informativi
7 Debugging Messaggi di debug
The message continues with an indication of the date and time, the name of the device that sent the message
Hostname and message text Message.
Syslog server
A SYSLOG server is a central point where to get all the error messages of the various hardware devices and software
on a network such as routers, switches, servers, printers, etc for centralized control of the errors of the equipment.
SYSLOG is particularly common in unix and consequently under linux, in windows there are some freeware and/or
commercial programs to manage syslog server. The server can select (filter) incoming messages based on various
criteria, each selection is at least one share.
In practice this is to establish selection criteria and the action to take depending on the source and type of message
The selection criterion can be for example:
Priority, IP address of the sender of the message, Hostname, text (or part of it) of the message, time interval of one or
more days of the week.
The actions can be for example:
None (ignore the message), View it in the monitoring program, Send it to another Syslog server, Issuing an alarm
sound, run a program, send an e-mail, Save the message in a database (eg MySQL), Save the message in a log file,
run a script, etc.
For my needs I used Syslog Watcher (Site http://www.snmpsoft.com), an excellent free program, below is a screenshot
with the display of notifications sent by a system SlimLine.
As you can see the various notices are divided by color according to their importance and in the message text can
include any information such as code operator who has had access to entry detected by an RFID reader.
Type Library
7.21.1 SysLogReport, send a report to Syslog server
FB eLogLib_B000
This function block sends a notification messages to a Syslog server whose IP address is
defined in SyslogIP and the port in SyslogPort. This function block is protected and require a
code to unlock it (see functions and function blocks protection). It is possible to use it freely in
test mode for 30 min.
It's possible to set the Facility code, the Severity and the name of the host system
HostName.
By activating the Send input a notification is sent to a Syslog server, executed the sending the
Done output is set for a program loop, if an error is detected the Fault output is set for a
program loop.
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10034020 Protected FB. The available time for demo mode is over.
10034080 FB used in a fast or slow task.
10034100 Syslog server not reachable, it doesn't answer to a ping.
Examples
In the following example are acquired the logic I/O on CPU module, using the two inputs you can send a notification
message to the syslog server with IP 192.168.0.81 on port 514 UDP.
Defining variables
LD example
Type Library
7.21.2 StringToLogFile, store string to a log file
FB eLogLib_B000
This function block logs the StringToLog string into the file Filename. Each line is
terminated with CR-LF. When the MaxRowsInFile lines are reached in the file, if
Circular is set, the new log string are written starting fom the beginning so overwriting
the existing lines. If Circular is not set the string is not written in the file and an error
occours.
The variable MaxRowsLen allows to limit the maximum length of each line in the log
file. When Circular is set, if the length of StringToLog is less than MaxRowsLen,
some space characters are added to the StringToLog to have a length equal to
MaxRowsLen. In RowIndexPtr must enter the address of the variable used as an
index of the next row in which to log. Normally this variable must be buffered to allow
you to write in the right place even after a power-off system. If you do not use a
variable buffer at each switch-off, it will restart to write logs from the beginning of the
file. So you can choose the desired behavior.
This function block is protected and require a code to unlock it (see function and function block protection). It is
possible to use it freely in test mode for 30 min.
By activating the Write input the StringToLog string is stored on the file and then the Done output is set for a program
loop. In case of execution error the Fault output is set for a program loop.
Enable (BOOL) Enables the function block.
Write (BOOL) Write StringToLog to file.
StringToLog (STRING[160]) String to be written in the file.
Filename (STRING[32]) Filename and path where to write the logs (ie.: 'SDCard/MyFile.txt').
Circular (BOOL) Indicates if to execute the circular logs or not.
MaxRowLen (USINT) String to log length limit.
MaxRowsInFile (UDINT) Number of log rows in the log file.
RowIndexPtr (@UDINT) Pointer to the variable used as an index of the next line of log.
Enabled (BOOL) Set if the function block is enabled.
Done (BOOL) Set for a program loop when the log string is written in the file.
Fault (BOOL) Set for a program loop if an error occours.
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10035020 Protected FB. The available time for demo mode is over.
10035080 FB used in a fast or slow task.
10035100 The MaxRowLen value is too large.
10035110 Maximum number of log entries reached.
10035120 Error on opening file.
10035130 File positioning error.
10035140 File write error.
10035150 File close error.
Examples
In the following example when the Di00M00 input is set, the string present in the variable Str is saved in the file
SDCard/MyLog.txt. Having Circular set, when 10 logs are saved the eleventh overwrites the first. The LogIndex
variable is a variable mapped in the RETAIN area.
Defining variables
LD example
Type Library
7.21.3 FileMemoryDump, dump memory on file
FB eLogLib_B000
This function block performs a memory dump of a memory area starting at address
MBufferPtr for the number of bytes defined MBufferSize on a disk file Filename.
With a pulse command on Write input the file is created and the contents of the memory is
written to the file. With a pulse command on Read input the file is read and its contents is
written into the memory.
When the command is end the Done output is set for a program loop, in case of execution
error the Fault output is set for a program loop.
The dump file on disk is an ascii file so you can edit it with any text editor, here's a sample
file.
00000000: 00 AB 12 34 00 00 00 00 | 00 00 00 12 00 0F 0A CC
00000010: 02 00 00 00 00 00 00 00 | EF C0 DD 00 00 00 01 00
Error codes
If an error occurs, the Fault output is activated, and SysGetLastError can detect the error code.
10036070 Execution cases error.
10036100 FB used in a fast or slow task.
10036200 Error on file opening.
10036210 Error on file positioning, read command.
10036220 Error on file read command.
10036230 Error on file write command.
10036240~4 Data failure on file dump, read command
10036400 Error on file opening, write command.
10036410 Error on file positioning, write command.
10036420 Error on file write, write command.
10036430 Error on file close, write command.
Example
In the following example on activation of the Di02M00 input, the contents of the memory buffer DumpBuffer, is written
on the Storage/Dump.txt file. After executing the write, by activating the Di01M00 input, the file is read back and the
data contains on it are transferred to the memory buffer.
Defining variables
LD example
PLC Node 2
MMasterDataTxfer
2 MyNode
DataTxferClient
0 ToNode
DataTxferClient
1 ToNode
DataTxferClient
3 ToNode
Radio Modem
Radio Modem
DataTxferClient DataTxferClient
1 ToNode 1 ToNode
DataTxferClient DataTxferClient
2 ToNode 2 ToNode
PLC Node 1
MMasterDataTxfer
BroadcastDataSend
1 MyNode
DataTxferClient
0 ToNode
DataTxferClient
2 ToNode
DataTxferClient
3 ToNode
Type Library
7.22.1 MMasterDataTxfer, multimaster data transfer
FB eMMasterDTxferLib_C000
This function block manage the interface with the I/O terminal defined in File to manage the
multimaster communication on multidrop network. This function block is protected and
require a code to unlock it (see functions and function blocks protection). It is possible
to use it freely in test mode for 30 min.
The function block acts as a server, managing the communication on the I/O device, some
function blocks clients are then connected to it, they manage the data exchange between
systems. The FB returns a MMDtTxfID to be passed to the FB client (Example
DataTxferClient).
In MyNode the system node number must be defined, on a network the node number must
be unique. All messages with have as a destination node the value of MyNode will be
received and then passed to the FB clients for verification.
The multimaster communication is based on the control of the communication channel free and the collisions
management, the parameters that controls this operation are set in MinFreeTm and MaxFreeTm. A small time will be
set for communications over the serial line and higher time in case of communication via radio modem.
In MinChkTm and MaxChkTm you can set a time for sending a control message to other network systems. The FB
sequentially will enable the various FB clients to exchange data to the peer with which the FB dialogue checking if the
communication is working properly. If one or both values are set to 0, the check is not executed.
In RxErrors is returned the reception error count, the FB continuously monitors the communication channel and if the
received data is on error the counter is incremented. Errors may occur in case of collision on the communications
channel. In case of execution error is set for for a loop the Fault output.
Enable (BOOL) Enables function block.
File (FILEP) Stream returned from Sysfopen function.
MyNode (USINT) System node ID (Range from 0 to 250).
MinFreeTm (REAL) Minimum waiting time for the communication channel free (S).
MaxFreeTm (REAL) Maximum waiting time for the communication channel free (S).
MinChkTm (REAL) Minimum waiting time to sending check frame to peer (S).
MaxChkTm (REAL) Maximum waiting time to sending check frame to peer (S).
Enabled (BOOL) FB enabled.
Fault (BOOL) Active for a program loop if there is a management error.
MMDtTxfID (UDINT) Server ID to pass to FB clients (Example DataTxferClient).
RxFrames (UDINT) Data frame received counter. All frames are counted regardless the node they are directed.
TxFrames (UDINT) Data frame transmitted counter.
RxErrors (UDINT) Data frame received error counter.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10040010 File not defined.
10040020 Protected FB. The available time for demo mode is over.
10040050 Execution timeout.
10040070 Wrong execution case.
Type Library
7.22.2 DataTxferClient, Data transfer client
FB eMMasterDTxferLib_C000
This function block exchanges data with another system on a communication channel. It
connects to the MMasterDataTxfer function block that manages the communication device,
must be passed the MMDtTxfID on output from the server function block.
The function block exchanges data with the system defined in ToNode. In practice, the value
of ToNode must match the value of MyNode of the MMasterDataTxfer FB on the other
system.
In RxData and TxData must be defined the address of data buffer that you want to exchange
with the peer system. DLen defines the size in bytes of the exchange data buffer (The RxData
and TxData buffers must have the same size). The FB checks whether there is a variation of
the data in the TxData buffer and immediately transmit them to the peer that responds with the
data in its TxData buffer, the received data will be transferred into the RxData buffer.
The PeerOk output is active if communication with the peer system is operational in the event of communication failure
the output is disabled. In RxFrames and TxFrames are returned the count of data frames received and sent by the FB
to the peer system, in AckErrors is returned the number of acknowledge errors. In case of execution error is set for a
loop the Fault output.
Enable (BOOL) Enables function block.
MMDtTxfID (UDINT) Server ID on output from the MmasterDataTxfer FB.
ToNode (USINT) Node ID of the peer system on which to exchange data (Range from 0 to 250).
RxData (@USINT) Pointer to the buffer where the received data must be transferred.
TxData (@USINT) Pointer to the buffer where are the data to be transmitted.
DLen (UDINT) Number of exchanged bytes (Max 32).
Enabled (BOOL) FB enabled.
Fault (BOOL) Active for a program loop if there is a management error.
RxOk (BOOL) Active for a program loop when data is received from peer.
PeerOk (BOOL) On when data exchange with the peer system is ok.
RxFrames (UDINT) Rx frame counter.
TxFrames (UDINT) Tx frame counter.
AckErrors (UDINT) Peer system acknowledge errors
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10041010 MMDtTxfID not defined.
10041020 Wrong MMDtTxfID.
10041050 DLen value out of range.
10041200 Data frames received from the peer system has incorrect length. Check DLen on peer system.
Examples
In the example is managed the exchange of 8 BOOL with the system peer node 1 (MyNode=1).
Defining variables
LD example
Type Library
7.22.3 BroadcastDataSend, broadcast data send
FB eMMasterDTxferLib_C000
This function block performs the broadcast data transmission. It connects to the
MMasterDataTxfer function block that manages the communication device, must be passed
the MMDtTxfID on output from the server function block.
The function block sends the data in the buffer pointed to by TxData with broadcast address
16#FF. All systems running the FB DataTxferClient who ToNode is equal to the value defined
in the Node parameter of MMasterDataTxfer, receive the data sent.
In TxData need to define the address and in DLen the size in bytes of the data buffer you want
to exchange with peer. To each activation of the Enable input the data is sent in broadcast, when sending is finished
the Done output is activated and remains active until the deactivation of Enable. To make a new transmission must be
disabled and then re-enable the Enable input.
Enable (BOOL) FB enable
MMDtTxfID (UDINT) Server ID on output from the MmasterDataTxfer FB.
TxData (@USINT) Pointer to the buffer where are the data to be transmitted.
DLen (UDINT) Number of exchanged bytes (Max 32).
Done (BOOL) Active when data is sent, remain active until Enable is deactivated.
Fault (BOOL) Active for a program loop if there is a management error.
TxFrames (UDINT) Tx frame counter.
Codici di errore
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10044010 MMDtTxfID not defined.
10044020 MMDtTxfID not correct.
10044050 DLen value out of range.
As you can see to each message is associated the text and the variables to be displayed. In the message can be
displayed all global variables.
Compiling the project LogicLab creates and instantiates for each HMI a HMIBuiltInMessages function block, named
with the HMI name, in the example shown above MyHMI. This FB manages the messages and variables but to display
them a terminal management FB must be connected to it.
Type Library
7.23.1 HMIBuiltInMessages, HMI built in messages
FB eHMIBuiltInLib_B000
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10046010 LogicLab messages table not supported.
10046020~2 Memory allocation not possible.
10046100 FB not executed in background (Back) task.
10046200 Message ID request on ViewMID not found.
10046100 Not enough space to display variable.
Type Library
7.23.2 HMIBuiltInNetlog, Netlog HMI management
FB eHMIBuiltInLib_B000
This function block manages the NetlogIII terminal (display and keyboard) integrated into
the system, it must be executed on Back task. It connects to HMIBuiltInMessages
management messages function block. The HMIBuildInID of the function block must be
connected to the input.
By activating the Enable input the Enabled output is activated and the terminal is managed
displaying the messages defined in the LogicLab terminal. In the File input must be passed
the terminal I/O stream (returned by the function Sysfopen).
The FB returns the state of all the terminal keys and this allows to use them in your program
as a commands. The SpyOn input if active allows to spy the FB operations.
In case of execution error the Fault ouput is set for a program loop.
TFlags Description
16#00000001 Rx: Data received from terminal.
16#00000002 Tx: Display command sent.
16#00000004 Tx: Display data sent.
16#00000008 Tx: Input data command sent.
File (FILEP) Terminal I/O stream as returned by the Sysfopen function.
ALevel (USINT) Access Level pattern to messages.
HMIBuiltInID (UDINT) Management messages ID as returned bu the HMIBuiltInMessages FB.
Enabled (BOOL) Active if the FB is enabled.
Ready (BOOL) Active if the Netlog terminal hardware is ready.
Fault (BOOL) Active for a program loop on error.
KeyUP (BOOL) UP key state, on terminal.
KeyDW (BOOL) DW key state, on terminal.
KeyLEFT (BOOL) LEFT key state, on terminal.
KeyRIGHT (BOOL) RIGHT key state, on terminal.
KeyFUN (BOOL) FUN key state, on terminal.
KeyENT (BOOL) ENT key state, on terminal.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10047010 HMIBuildInID not defined.
10047020 HMIBuildInID not correct.
10047100 FB not executed in background (Back) task.
Example
In this example a NetlgIII terminal is managed, the messages has been defined in the LogicLab program with the
MyHMI name.
Defining variables
ST example
(* Here open the terminal communication port. *)
IF (SysFirstLoop) THEN
HMI.File:=Sysfopen('PCOM0.1', 'rw'); (* File pointer *)
END_IF;
Type Library
7.23.3 HMIPicoface, Picoface HMI management
FB eHMIBuiltInLib_B200
This function block manages the Picoface terminal, the terminal can be connected to the I2C
system bus extension or by serial both in RS232 FullDuplex or in RS485 HalfDuplex. The
CType parameter specify the communication used.
The FB must be run in Task Back. It connects to HMIBuiltInMessages management
messages function block. The HMIBuildInID of the function block must be connected to the
input.
By activating the Enable input it activates the Enabled output and the Picoface terminal is
managed, viewing messages defined in the terminal from LogicLab. In the File parameter
must be passed the I/O deice stream used to manage (Is the return of the Sysfopen
function).
Activating the input bits is possible to control the LEDs and outputs on the terminal, in the
outputs are returned to the state of the keys and the terminal input. This allows to use them
as commands in our program.
It's provided the management of a One Wire device, the FB in OneWireData returns an
array with the data reported below.
Where:
DP: Device Protocol.
DF: Device family.
The SpyOn input if active allows to spy the FB operations.
If an error running is activated for a loop the Fault output.
OneWireOk (BOOL) Active if at least one One-Wire device connected to the terminal connector.
OneWireTrig (BOOL) Active for a program loop, it must be used as trigger to read OneWireData array.
OneWireData (BYTE[16]) Returns the data read from the device connected to the terminal connector.
FKey0~9 (BOOL) Function keys from [0] to [9] status.
KeyFUN (BOOL) FUN key status.
KeyESC (BOOL) ESC key status.
KeyCLR (BOOL) CLR key status.
KeyENT (BOOL) ENT key status.
KeyUP (BOOL) UP key status.
KeyDOWN (BOOL) DOWN key status.
Inp0~1 (BOOL) Digitalò inputs stayus.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10049010 HMIBuildInID not defined.
10049020 HMIBuildInID not correct.
10049100 FB not executed in background (Back) task.
Esempi
In this example a Picoface terminal is managed, the messages has been defined in the LogicLab program with the
MyHMI name.
Defining variables
ST example
(* Here open the terminal communication port. *)
IF (SysFirstLoop) THEN
HMI.File:=Sysfopen('PCOM15.1', 'rw'); (* File pointer *)
END_IF;
12Vdc 12Vdc
2k2 10k 1k
BC847 BC847
10k
Bidirectional data
(CCTalk)
GND (CCTalk)
Type Library
7.24.1 ccTalkProtocol, manages ccTalk protocol
FB eCCTalkProtoLib_A000
This function block manges the protocol, it must be connected to a serial port file to
which you connect the cctalk devices. This function block is protected and require a code
to unlock it (see functions and function blocks protection). It is possible to use it
freely in test mode for 15 min.
The FB returns a CCTalkProtoID that must be passed to the linked FB for the
management of the various devices connected ccTalk. The SpyOn if active allows you to
spy on the FB operations.
The Fault output is activated for a program loop in case of error.
Enable (BOOL) Protocol management enable.
SpyON (BOOL) Active allows to spy the FB working.
File (FILEP) Stream returned by Sysfopen function.
Enabled (BOOL) Active on Enable command.
Fault (BOOL) Active for a program loop if management error.
CCTalkProtoID (UDINT) Protocol ID to pass to linked FBs.
Trigger di spy
If SpyOn is active the SysSpyData function is executed this allows to spy the FB operations. There are various levels
of triggers.
TFlags Description
16#00000001 'Tx' ccTalk command sent.
16#00000002 'Rx' ccTalk answer received.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
Code Description
10050010 File value not defined.
10050020 The FB is not executed on background (Back) task.
10050030 Protected FB. The available time for demo mode is over.
10050100 Communication timeout
10050200~4 Error in the sequences of sending command.
10050300~4 Error in the sequences of receiving command.
Type Library
7.24.2 AlbericiAL66, Alberici AL66 coin acceptor
FB eCCTalkProtoLib_A000
This function block manages a Alberici coin acceptor model AL66V, it must be linked
with the ccTalkProtocol that manages the ccTalk protocol.
By activating the Enable input the dialogue with the coin acceptor with address defined
in DAddress, starts. The FB communicates continuously with the acceptor sending
commands every time defined in CDelay. I remember that to accept the coins, acceptor
must be interrogated via cctalk at least every 500 mS.
The CEnable parameter allows you to define the currencies accepted by the acceptor,
there is a bit pattern of 16 bits, where each bit corresponds to a type of currency (Refer
to the acceptor documentation).
If the inserted coin is accepted the CoinOk is set for a program loop and on the CAccepted output (Bit pattern 16 bits)
is set the bit relate to the currency accepted.
In case of error execution Fault is set for a program loop and Errors is incremented.
Enable (BOOL) Enables the FB
CCTalkProtoID (UDINT) Protocol management ID (From ccTalkProtocol.FB).
DAddress (USINT) Device address, identifies the device to communicate with.
CEnable (WORD) Coins enable, coins enable bit pattern.
CDelay (UINT) Command delay, delay between commands (mS).
CoinOk (BOOL) Active for a program loop if coin is been accpted.
Fault (BOOL) Active for a program loop if management error.
CAccepted (WORD) Coin accepted, coin accepted indicator, bit pattern.
Errors (UDINT) Execution error counter.
Error codes
If an error occurs, the Fault output is activated and SysGetLastError can detect the error code.
10051010 HMIBuildInID not defined.
10051020 HMIBuildInID not correct.
10051030 The FB is not executed on background (Back) task.
10051040 Too many Fbs, not possible to execute.
10051100 Device communication error.
Example
In the example an Alberici AL66V electronic coin acceptor with ccTalk protocol is managed. The
sample program defines the coins that can be accepted and counts the accepted coins
according to their values.
Defining variables
ST example
(* ---------------------------------------------------------------------- *)
(* INIZIALIZZAZIONI *)
(* ---------------------------------------------------------------------- *)
(* Eseguo inizializzazioni. *)
IF (SysFirstLoop) THEN
i:=SysGetSerialMode(ADR(Sm), Fp);
Sm.Baudrate:=9600; (* Baud rate *)
Sm.Parity:='N'; (* Parity *)
Sm.DataBits:=8; (* Data bits *)
Sm.StopBits:=1; (* Stop bits *)
Sm.DTRManagement:=DTR_AUTO_WO_TIMES; (* DTR management *)
Sm.DTRComplement:=FALSE; (* DTR complement *)
Sm.EchoFlush:=FALSE; (* Echo flush *)
Sm.DTROffTime:=0; (* DTR off time *)
Sm.DTROnTime:=0; (* DTR on time *)
i:=SysSetSerialMode(ADR(Sm), Fp);
(* ---------------------------------------------------------------------- *)
(* GESTIONE PROTOCOLLO CCTALK *)
(* ---------------------------------------------------------------------- *)
(* Gestione del protocollo ccTalk. *)
(* ---------------------------------------------------------------------- *)
(* GESTIONE ACCETTATORE ALBERICI *)
(* ---------------------------------------------------------------------- *)
(* Gestione accettatore Alberici. *)
Acpt.CCTalkProtoID:=CCTalk.CCTalkProtoID; (* Protocol ID *)
(* ---------------------------------------------------------------------- *)
(* Definizione monete accettate da accettatore. Viene definita maschera *)
(* ---------------------------------------------------------------------- *)
(* CALCOLO DENARO INSERITO *)
(* ---------------------------------------------------------------------- *)
(* Controllo se moneta acettatta da accettatore. *)
IF (Acpt.CoinOk) THEN
NrOfCoins:=NrOfCoins+1; (* Numero di monete inserite *)
CASE (Acpt.CAccepted) OF
16#0001: Credit:=Credit+200; (* 2 Euro *)
16#0002: Credit:=Credit+100; (* 1 Euro *)
16#0004: Credit:=Credit+50; (* 50 Centesimi *)
16#0008: Credit:=Credit+20; (* 20 Centesimi *)
16#0010: Credit:=Credit+10; (* 10 Centesimi *)
16#0020: Credit:=Credit+5; (* 5 Centesimi *)
16#0040: Credit:=Credit+2; (* 2 Centesimi *)
16#0080: Credit:=Credit+1; (* 1 Centesimo *)
END_CASE;
END_IF;
(* [End of file] *)
8 Communication protocols
From software version SFW167D000 the addressable area is also in the range from 20000 to 2xxxx.
In the functions that access the single-bit (every bit equals to one byte of memory), the address of the variable in
Note 1)
the command is used. So having to access to the MX100.50 location, the address value will be 40050.
Note 2)In the functions that access the registers (16 bits) the address of the variable divided by 2 is used. So having to
reach the MX100.50 location, the value 40025 will be used.
The registers (16 bits) of the real time clock are allocated in consecutive locations starting from the Modbus address
100. The registers contain the current value of the real time clock and writing a new value, the the real time clock will be
automatically updated.
Command frame: 01 10 00 63 00 06 08 00 1E 00 30 00 0B 00 1D 00 09 07 DA 5D C8
Answer frame: 01 10 00 63 00 06 B0 15
Modbus TCP/IP frames
Command frame: 00 00 00 00 00 13 01 10 00 63 00 06 08 00 1E 00 30 00 0B 00 1D 00 09 07 DA
Answer frame: 00 00 00 00 00 06 01 10 00 63 00 06
Here's the view of the file system at the connection. Project and System folders are reserved for system use and you
should not change its contents. The files of the user pages can be transferred in the Storage and SDCard (if present)
folders.
So the user can create his own web pages using any HTML editor but also simply by using a simple text editor such as
Notepad, of course it's needed to know the HTML syntax. The created pages will be transferred in the desired directory
and accessing to them by a browser the page will be displayed.
Saving the above text in a file, such as SPage.htm, and transferring it to the Storage directory of the SlimLine, you can
see the resulting web page by simply typing in the browser the page address.
Of course, the page can contain links to other pages, it will be possible to achieve a personal navigation between
different pages. Here is the same example as before with included the definition of a style.
Html source page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>SlimLine - Simple page</title>
<style type="text/css">
.Bolded {font-family: Arial, Helvetica, sans-serif; font-size: 20px; font-style: normal;font-weight: bold;}
</style>
</head>
<body>
This page is served by the <span class="Bolded">SlimLine</span>
</body>
</html>
Saving the above text in a file, such as DPage.htm, and transferring it to the Storage directory of the SlimLine, you can
see the resulting web page by simply typing in the browser the page address.
As can be seen, the top row shows the value of the PLC DB100.10 while setting a value in the text box in the bottom
row and then pressing the Save button, you can set the value of the DB100.12.
Of course in a web page can be displayed and can be set all the desired variables, it is advisable not to go overboard
with the number of variables, it is preferable to split them into multiple pages.
Flags
+ The visualization of signed variables, will always start with the - or + signs.
space The visualization of signed variables, will always start with the space or – sign.
x Values other than 0 are prefixed with 0x.
0 At the displayed value are added 0 until the desired number of digits (Only for variables of type d, i, o, u,
x, X, e, E, f, g, G).
Conversion
d Decimal value with sign.
i Decimal value with sign.
o Octal value without sign.
u Decimal value without sign.
x Hexadecimal value is displayed using lowercase letters (From 0 to 9, from a to f).
X Hexadecimal value is displayed using uppercase letters (From 0 to 9, from A to F).
e Decimal floating-point value, displayed on exponential notation (Example: [-]d.ddde+dd).
E Decimal floating-point value, displayed on exponential notation (Example: [-]d.dddE+dd).
f Decimal floating-point value (Example: [-]d.ddd).
c Single character.
s String.
Pratically a <form> field with id MyForm contains a text box of 5 characters with a maximum of 10 characters with id
UINT12. In the form is also placed a button of submit type which pressure sends the whole form.
By defining in the browser the value of the text box and pressing the Save button, the defined data will be sent to the
server that will display the page DPage.htm and at the same time it will write the defined value in the UINT DB100.12
variable.
TARG name
The name field of the argument is very important, it defines the type of PLC variable to be set (All types defined in
IEC61131 are managed) and its address, the two fields must be separated by a space.
A name like UINT 12 will indicate a UINT variable allocated to address DB 100.12.
A name like REAL 128 will indicate a REAL variable allocated to address DB 100.128.
A name like STRING 1000 16 will indicate a STRING 16 chars length variable, allocated to address DB 100.1000.
9.4.1 ARG id
The id field of the argument is used to reference the object within the form by the SetValues() function. The choice to
define it UINT12 used in the example is just an example, it would be better to use a definition that remind to the
meaning (Example "SetPoint", "Preset", etc.).
function SubmitForm(Form)
{
if (document.getElementById('Out00').checked) document.getElementById('BOOL3').value="1";
if (document.getElementById('Out01').checked) document.getElementById('BOOL4').value="1";
document.forms[Form].submit();
}
</script>
// *****************************************************************************
// "SFW191A000" FUNZIONI PER GESTIONE AJAX
// *****************************************************************************
// Le seguenti funzioni gestiscono lo standard AJAX "Asynchronous Java and XML",
// con esse viene gestito lo scambio dinamico di dati con le pagine web.
// *****************************************************************************
// FUNZIONE "SetupValues(PContent)"
// *****************************************************************************
// Questa funzione viene eseguita su risposta Ajax, nella variabile "PContent"
// è presente tutto il contenuto della pagina richiesta.
// -----------------------------------------------------------------------------
function SetupValues(PContent)
{
var Value=new Array(); //Array valori ricevuti da server
if (PContent.indexOf('|') != -1)
{
Value=PContent.split('|');
document.getElementById("Angle").value=Value[0];
document.getElementById("Sin").value=Value[1];
document.getElementById("Cos").value=Value[2];
}
}
</script>
</head>
<body onLoad="setInterval('AJAXSendRequest(\'Values.htm\')', 3000)">
<table border="0">
<tr>
<td>Angle:</td>
<td><input type="text" id="Angle" size="4" maxlength="4"/></td>
<td>Sin:</td>
<td><input type="text" id="Sin" size="6" maxlength="6"/></td>
<td>Cos:</td>
<td><input type="text" id="Cos" size="6" maxlength="6"/></td>
</tr>
</table>
</body>
</html>
On page load <body onLoad="setInterval('AJAXSendRequest(\'Values.htm\')', 3000)"> the AJAX request of the
page Values.htm is performed every 3 seconds. The return value of this page is automatically passed to the function
SetupValues that it parse it and copy the values on the display objects. The page Values.htm returns the values of the
3 variables separated by the | symbol. Here's the listing for this page.
Values.htm source page
<!--['%d', UINT, 0]-->|<!--['%6.3f', REAL, 4]-->|<!--['%6.3f', REAL, 8]-->
LD example
IL example
LD 16#12345678
ROL 16
ST VarOut (* Output variable *)
ST example
VarOut:=ROL(16#12345678, 16); (* Output variable *)
LD example
IL example
LD 16#1234
ROL 8
ST VarOut (* Output variable *)
ST example
VarOut:=ROL(16#1234, 8); (* Output variable *)
LD example
IL example
LD 16#12
ROL 4
ST VarOut (* Output variable *)
ST example
VarOut:=ROL(16#12, 4); (* Output variable *)
Here's an example of using the SysVarfprintf function to define printable characters and non printable characters, and
send them to the output stream. In this example, is sent to the serial port COM0 the [Ciao] string followed by carriage
return and line feed.
Defining variables
LD example
ST example
(* Rx data from stream. *)
WHILE (TO_BOOL(SysGetIChars(File))) DO
@Ptr:=TO_USINT(Sysfgetc(File)); (* Rx string *)
Ptr:=Ptr+1; (* String pointer *)
To the data transmission to the stream, the SysGetOSpace function is used to check if there is enough space to hold
the string, or as in the example, if the output buffer is empty, then it's possible to send the string with the SysVarfprintf
function.
Defining variables
ST example
(* Tx data to stream. *)
Example
Convert a variable DINT variable to a USINT variable in different programming languages. Of course, if the VarDINT
variable value exceeds the value 255 (Limit of the VarUSINT variable), the rest of the division for the value and the limit
will be returned.
Defining variables
IL example
LD VarDINT (* DINT variable *)
TO_USINT
ST VarUSINT (* USINT variable *)
FBD example
LD example
ST example
VarUSINT:=TO_USINT(VarDINT); (* USINT variable *)
In the example a simple program that reads the values of variables SysUSet(x) and transfers them to the respective
SysUInfo(x) variable. In the web page, the value set in the SysUSet(x) variable, on acceptance with the Write button, is
returned in the SysUInfo(x) variable, as shown in the screenshot above.
Definizione variabili
Esempio ST
(* Read user settings and write user infos. *)
IF (SysUVSet) THEN
i:=SysVarsscanf(ADR(SysUSetA), '%d', UDINT_TYPE, ADR(Values[0]));
i:=SysVarsnprintf(ADR(SysUInfoA), 16, '%d', UDINT_TYPE, ADR(Values[0]));
11 Programming examples
Once included in the project the samples, it will be possible to use them directly, or, with simple cut and paste operations,
pasting part of the source code from the sample.
Then you must define the communication mode from the menu On-line → Set up communication.
12 Appendix
Negation -
Complement NOT
Exponentiation **
Multiply *
Divide /
Modulo MOD
Add +
Subtract -
Comparison < , > , <= , >=
Equality =
Inequality <>
Boolean AND &
Boolean AND AND
Boolean Exclusive OR XOR
Boolean OR OR
Statement Example
Assignment A:=B; CV:=CV+1; C:=SIN(X);
RETURN RETURN;
IF D:=B*B-4*A*C;
CASE TW:=BCD_TO_INT(THUMBWHEEL);
TW_ERROR:=0;
CASE TW OF
1,5: DISPLAY:=OVEN_TEMP;
2: DISPLAY:=MOTOR_SPEED;
3: DISPLAY:=GROSS-TARE;
4,6..10: DISPLAY:=STATUS(TW-4);
ELSE
DISPLAY:=0;
TW_ERROR:=1;
END_CASE;
QW100:=INT_TO_BCD(DISPLAY);
FOR J:=101;
WHILE J:=1;
REPEAT J:=-1;
REPEAT
J:=J+2;
UNTIL J=101 OR WORDS[J]='KEY'
END_REPEAT ;
EXIT EXIT;
Empty Statement ;