Notes on the documentation

This description is only intended for the use of trained specialists in control and automation engineering who are familiar with the applicable national standards.
It is essential that the following notes and explanations are followed when installing and commissioning these components.

The responsible staff must ensure that the application or use of the products described satisfy all the requirements for safety, including all the relevant laws, regulations, guidelines and standards.

Disclaimer

The documentation has been prepared with care. The products described are, however, constantly under development.
For that reason the documentation is not in every case checked for consistency with performance data, standards or other characteristics.
In the event that it contains technical or editorial errors, we retain the right to make alterations at any time and without warning.
No claims for the modification of products that have already been supplied may be made on the basis of the data, diagrams and descriptions in this documentation.

Trademarks

Beckhoff®, TwinCAT®, EtherCAT®, Safety over EtherCAT®, TwinSAFE® and XFC® are registered trademarks of and licensed by Beckhoff Automation GmbH.
Other designations used in this publication may be trademarks whose use by third parties for their own purposes could violate the rights of the owners.

Patent Pending

The TwinCAT Technology is covered, including but not limited to the following patent applications and patents:
EP0851348, US6167425 with corresponding applications or registrations in various other countries.

Copyright

© Beckhoff Automation GmbH & Co. KG, Germany.
The reproduction, distribution and utilization of this document as well as the communication of its contents to others without express authorization are prohibited.
Offenders will be held liable for the payment of damages. All rights reserved in the event of the grant of a patent, utility model or design.


Overview

The library contains useful function blocks for the PLC Controller (BCxxxx Controller). Additionally the library contains a functionblock for the decoding of the DCF-77 time signal.

Requirements

Newer firmware version of the PLC Controller is required. Please see in the PlcSystemBC library documentation.

Contents of the library:

Functionblock

Name | Description
RTC | Real Time Clock
RTC_EX | Real Time Clock with additional millisecond output
DCF77_TIME | Read DCF77 radio time
ReadWriteTerminalReg | Reads/writes to terminal registers
DRAND | Random number generator
FB_BasicPID | Simple PID controller

Functions

Name | Description
DT_TO_SYSTEMTIME | Converts DATE_AND_TIME to the Windows SYSTEMTIME struct
SYSTEMTIME_TO_DT | Converts Windows SYSTEMTIME struct to DATE_AND_TIME
TIME_TO_OTSTRUCT | Converts TIME to structure with milliseconds, seconds, minutes, hours, days and weeks
OTSTRUCT_TO_TIME | Converts structure with milliseconds, seconds, minutes, hours, days and weeks to TIME variable
SETBIT32 | Sets one bit of 32 bit variable to 1
CSETBIT32 | Sets one bit of 32 bit variable to 1or 0
GETBIT32 | Gets one bit value of 32 bit variable
CLEARBIT32 | Clears one bit of 32 bit variable to zero
F_SwapReal | Converts bus controller REAL variables in the 4 Byte REAL Intel format
IsFinite | Checks if REALvariable can be represented in Institute of Electrical and Electronics Engineers (IEEE) format.

Data structures

Name | Description
TIMESTRUCT | Structure of the Windows system time structure
OTSTRUCT | Structure of the operating time structure


RTC

TwinCAT PLC Library: Utilities BC

FUNCTION_BLOCK RTC

The "RTC" (Real Time Clock) function block allows an internal clock to be implemented within a PLC controller (BCxxxx). The clock must be initialised with a starting date and time. After initialisation, the time and date are updated cyclically each time the function block is called. A controller system clock is used to calculate the current time and date. The system clock has a resolution of one millisecond. The function block should be called in every PLC cycle, so that the current time can be calculated. The RTC has a potential error of about 1 minute in each 24 hours. In order to avoid large errors, the RTC can be cyclically synchronised (e.g. with a radio clock or with a TwinCAT PC via the fieldbus). The current date and time are available in the usual DATE_AND_TIME (DT) format at the function block's output. Multiple instances of the RTC function block can be created within one PLC program.

VAR_INPUT

VAR_INPUT
EN : BOOL;
PDT : DATE_AND_TIME;
END_VAR

EN: The function block is re-initialised with a specified date and time by a rising edge at this input.
PDT: ( Preset Date and Time ) The initialisation values for the function block's date and time. A rising edge at the EN input will cause the function block to adopt this value.

VAR_OUTPUT

VAR_OUTPUT
Q: BOOL;
CDT : DATE_AND_TIME;
END_VAR

Q: This output is set if the function block has been initialised at least once. If the output is set, the values for the date and time at the PDT output are valid.
CDT: ( Current Date and Time ) The current date and time from the RTC. The CDT output is only updated when the function block is called. For this reason, instances of the function block should be called once in each PLC cycle.

Example of a call in FBD:

PROGRAM MAIN
VAR
    RTC1 		: RTC;
    Init_RTC 		: BOOL;
    RTC_DataValid 	: BOOL;
    RTC_DateAndTime 	: DT;
END_VAR

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


RTC_EX

FUNCTION_BLOCK RTC_EX

The "RTC_EX" function block allows an internal clock to be implemented within a PLC controller (BCxxxx). The clock must be initialised with a starting date and time. After initialisation, the time and date are updated cyclically each time the function block is called. A controller system clock is used to calculate the current time and date. The system clock has a resolution of one millisecond. The function block should be called in every PLC cycle, so that the current time can be calculated. The RTC_EX function block has a potential error of about 1 minute in each 24 hours. In order to avoid large errors, the RTC_EX function block can be cyclically synchronised (e.g. with a radio clock or with a TwinCAT PC via the fieldbus). The current date and time are available in the usual DATE_AND_TIME (DT) format at the function block's output. In contrast to the RTC function block, RTC_EX has a precision of one millisecond. Since DATE_AND_TIME variables only have a precision of one second, the milliseconds are output via the CMSEK output variable. Multiple instances of the RTC_EX function block can be created within one PLC program.

VAR_INPUT

VAR_INPUT
EN : BOOL;
PDT : DATE_AND_TIME;
PMSEK : DWORD;
END_VAR

EN: The RTC_EX function block is re-initialised with a specified date, time and millisecond by a rising edge at this input.
PDT: ( Preset Date and Time ) The initialisation values for the function block's date and time. A rising edge at the EN input will cause the function block to adopt this value.
PMSEK: ( Preset Milliseconds ) The initialisation value for the milliseconds. A rising edge at the EN input will cause the function block to adopt this value.

VAR_OUTPUT

VAR_OUTPUT
Q : BOOL;
CDT : DATE_AND_TIME;
CMSEK : DWORD;
END_VAR

Q: This output is set if the function block has been initialised at least once. If the output is set, the values for the date, time and milliseconds at the PDT and CMSEK outputs are valid.
CDT: ( Current Date and Time ) The current date and time from the RTC. The CDT output is only updated when the function block is called. For this reason, instances of the function block should be called once in each PLC cycle.
CMSEK: (Current Milliseconds) The milliseconds output.

Example of a call in FBD:

PROGRAM MAIN
VAR
    RTC1			: RTC_EX;
    Init_RTC			: BOOL;
    RTCDataValid		: BOOL;
    RTC_DateAndTime		: DT;
    RTC_Milliseconds		: DWORD;
END_VAR

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


DCF77_TIME

FUNCTION_BLOCK DCF77_TIME

The "DCF77_TIME" function block can be used to decode the DCF-77 radio clock signal. A rising edge at the RUN input starts the decoding process, which continues as long as the RUN input remains set. In the worst case, the function block requires a maximum of 1 minute to synchronise itself, plus a further minute to decode the data for the following minute. It is waiting, during that time, for the missing 59th second marker. Internally the function block is sampling the DCF-77 signal. In order to be able to sample the edges without error the function block should be called once in each PLC cycle. Satisfactory results can be obtained with a cycle time of <= 25 ms. If the DCF-77 signal is absent or faulty, the ERR output is set TRUE, and a corresponding error code is set at the ERRID output. The ERR and ERRID outputs are reset the next time a correct signal is received. Some receivers provide an inverted DCF-77 signal. In such cases the signal must first be inverted before being passed to the DCF_PULSE input. When operating without errors, the current time is updated at the CDT output every minute. When this is happening, the READY output is set to TRUE for one PLC cycle in the first second (second zero). At this time the DCF-77 time at the CDT output is valid, and can be evaluated by the PLC program. The READY output is only set if it was possible to receive the data for the coming minute without errors.

The transferred parity bits are used for error detection. When reception is poor 100% error-free identification cannot be guaranteed, in the event of two defective (inverse) bits the function block cannot detect an error and will set the READY output to TRUE. In order to obtain reliable time information additional safeguards have to be implemented, e.g. redundancy analysis of the time information in consecutive minutes.

From TwinCAT v2.10 build > 1340 and TwinCAT v2.11 build > 1542 a simple plausibility check of two consecutive telegrams was implemented in the DCF77_TIME function block. This functionality can be activated via a global Boolean variable for all instances of the DCF77_TIME block. When the plausibility check is activated the first synchronisation is extended by a further minute to a maximum of 3 minutes.

GLOBAL_DCF77_SEQUENCE_CHECK : BOOL := FALSE;(* TRUE = Enable plausibility check (two telegrams are checked), FALSE = Disable check *)

Errors that occur during reception are registered by the function block. The ERRCNT output is an error counter. This counter indicates the number of errors that have occurred since the last correctly received signal. The counter is reset the next time a signal is correctly received.

Time Code

During each minute, the numbers that encode the year, month, day, day of the week, hour and minute are transmitted in BCD format through pulse modulation of the second marks. The transmitted information always describes the subsequent minute. A second marker is transmitted each second. A second marker with a duration of 0.1 s represents a binary zero, while a duration of 0.2 s represents binary one. The information is extended with 3 check bits. No second marker is transmitted for the 59th second, and a receiver can use this "gap" to synchronise itself.

From TwinCAT v2.10 build > 1340 and TwinCAT v2.11 build > 1542 the length of the short and long pulse signal can also be configured via a global variable. If the signal is poor the pulse widths are smaller. The receiver specification usually contains information about the minimum and maximum pulse for the two logic signals, with the higher value expected for higher field strengths and the lower value for low field strengths or in the event of interference. Problems may also occur near the sender (where the field strength is very large) and the pulse width of the logic zero may become excessive. For this reason a fixed limit is set for differentiating between zero and one, depending on the receiver specification. Check the specification of the receiver used and configure the impulse length accordingly.

GLOBAL_DCF77_PULSE_SPLIT : TIME := T#140ms;(* 0 == pulse < 140ms, 1 == pulse > 140 *)

E.g.: the Atmel T4227 specification (time code receive) contains the following pulse length specification:
100 ms pulses (zero): min: 70 ms, typical: 95 ms, max: 130 ms
200 ms pulses (one): min 170 ms, typical 195 ms, max 235 ms
For this IC a limit value of 150 ms would be ideal (130 + ( ( 170ms - 130ms ) / 2 )).

Tip:

If the configured limit value for the impulse length is too small, short impulses are detected as long. Conversely, if the configured limit value is too small, long impulses are detected as short. If the checksum is correct, the receiver cannot detect these errors. In the first case the receiver may supply times that are in future range, in the second case the times may be in the past.

VAR_INPUT

VAR_INPUT
    DCF_PULSE 	:BOOL;
    RUN 		:BOOL;
END_VAR

DCF_PULSE: The DCF-77 Signal.
RUN: A rising edge at this input initialises the function block and starts decoding the DCF-77 signal. If this input is reset, the decoding process is stopped.

VAR_OUTPUT

VAR_OUTPUT
    BUSY 		:BOOL;
    ERR 		:BOOL;
    ERRID 		:UDINT;
    ERRCNT 		:UDINT;
    READY 		:BOOL;
    CDT 		:DATE_AND_TIME;
END_VAR

BUSY: This output is set when the function block is activated.
ERR: This output is set when an error occurs in the decoding.
ERRID: Supplies the error number when the ERR output is set.
ERRCNT: The number of errors that have occurred since the last correctly received signal.
READY: If this output is set, the data at the CDT output is valid.
CDT: The DCF-77 time in DATE_AND_TIME format.

Error descriptions:

Error Codes | Error descriptions
0 | no error
0x100 | Timeout error. Possibly because no DCF-77 signal is detected.
0x200 | Parity error. Incorrect bits were detected in the received data.
0x300 | Incorrect data was received. Since the parity check can only detect one incorrect bit, the received data is checked again for validity (this error code will be generated, for instance, if month = 13).
0x400 | The last decoding cycle was too long. This error can occur when reception is poor (not enough second markers were received).
0x500 | The last decoding cycle was too short. This error can occur when reception is poor (additional edges were received).

Example of a call in FBD

In the example application the Real Time Clock is synchronised with the radio time signal as an error-free signal is received.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


ReadWriteTerminalReg

FUNCTION_BLOCK ReadWriteTerminalReg

The "ReadWriteTerminalReg" function block permits convenient access to the registers of the terminal via the terminal channel's status/control byte (register communication). In the standard operating mode, the data inputs and outputs of the intelligent terminal (e.g. an analog output terminal) are used to exchange the analog output data. A handshake via the status/control byte permits register access. The data input and output variables are used here to transfer the register values. The terminal has to be mapped as complex PLC terminal to see the status/control byte in the process view. If the terminal was mapped as compact PLC terminal or fieldbus terminal ( process view of the terminal for the bus controller not visible), the accesss to the registers of the terminal is not possible.
A rising edge at the READ or WRITE input causes the register with number REGNO to be read or written to. Write protection of the register is disabled by the function block for a write access and enabled once more afterwards. When a register is written to, the new register value is read, and is available at the CURRREGVALUE output. If changes made to the register values are to be stored permanently, the power supply to the coupler must be interrupted.

VAR_INPUT

VAR_INPUT
STATE: BYTE;
DATAIN            :
WORD;
REGNO             : BYTE;
READ              : BOOL;
WRITE             : BOOL;
TMOUT             : TIME;
NEWREGVALUE       : WORD;
END_VAR

STATE: Terminal channel status byte.
DATAIN: Terminal channel data input word.
REGNO: Number of the register that is to be written to or read.
READ: A rising edge at this input activates the block, and the current register value is read. If successful, the register value is available in the output variable CURRREGVALUE.
WRITE: A rising edge at this input activates the block, and the value in the input variable NEWREGVALUE is written into the register REGNO. After this, the current value of the register is read, and, if successful, is made available in the output variable CURREGVALUE.
TMOUT: States the length of the timeout that may not be exceeded during execution of the function.
NEWREGVALUE: Data word that is to be written into the register with number REGNO by a write access.

VAR_OUTPUT

VAR_OUTPUT
CTRL : BYTE;
DATAOUT : WORD;
BUSY : BOOL;
ERR : BOOL;
ERRID : UDINT;
CURREGVALUE : WORD;
END_VAR

CONTROL: Terminal channel control byte.
DATAOUT: Terminal channel data output word.
BUSY: This output is set when the block is activated, and remains set until execution of the function has been completed.
ERR: If an error should occur during the execution of the function, then this output is set, after the BUSY output has been reset.
ERRID: Supplies the error number when the ERR output is set.
CURREGVALUE: This variable provides the current register value after a successful read or write access.

Error descriptions:

Error number | Error descriptions
0 | no error
0x100 | Timeout error. The time permitted for execution has been exceeded.
0x200 | Parameter error (e.g. an invalid register number).
0x300 | The read value differs from the written value ( writing not allowed )

Examples of calls in FBD:

VAR
ReadWriteTerminalReg1                : ReadWriteTerminalReg;
State                     AT%IB0     : BYTE;
Control                   AT%QB0     : BYTE;
DataIn
AT%IW2     : WORD;
DataOut
AT%QW2     : WORD;
Start_ReadTerminalType               : BOOL;
Start_WriteFeatureRegister           : BOOL;
RWTerminalReg_Busy                   : BOOL;
RWTerminalReg_Err                    : BOOL;
RWTerminalReg_ErrId                  : UDINT;
TerminalType                         : WORD;
FeatureRegValue                      : WORD;
END_VAR

Example 1

In Example 1 the terminal identifier is read from register 8 of an analog output terminal. The variables State, Control, DataIn and DataOut are linked to the terminal's corresponding I/O variables in the TwinCAT System Manager. The terminal identifier is KL4002..

Example 2

In Example 2 the user-scaling is activated in the feature register (register 32) of a KL4002 analog output terminal. The new value in the feature register is then read by the function block, and can be checked through the output variable CURREGVALUE.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


DRAND

FUNCTION_BLOCK DRAND

Instances of function blocks are created according to IEC61131-3, and then called, or otherwise accessed, from with the PLC program using the instance names.
The function block permits generation of a (pseudo-) random number of type REAL.

VAR_INPUT

VAR_INPUT
    Seed 	: INT;
END_VAR

Seed : Initial value for specification of the random number series.

VAR_OUTPUT

VAR_OUTPUT
    Num 	: REAL;
END_VAR

Num : This output returns a pseudo-random number in the range 0.0 .. 1.0 with single accuracy. The generator here creates a number series with 1075 stochastic values per period.

Example of calling the block in FBD:

In the example the REAL value 0.643412 is generated and returned. The input parameter ”Seed" affects the initial value of the series. If, for instance, a deterministically reproducible random number series is desired in different sessions, and identical ”Seed" value must be used.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


F_REAL

FUNCTION F_REAL

Helper function, returns struct variable with additional REAL variable information.

FUNCTION F_REAL : T_Arg

VAR_IN_OUT

VAR_IN_OUT
    in	:REAL;
END_VAR
Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 Build > 522 TwinCAT v2.8.0 Build > 747 TwinCAT v2.9.0 Build > 947 | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


FB_BasicPID

TwinCAT PLC Libraries

FUNCTION_BLOCK FB_BasicPID

The function block represents a simple discrete PID element.

Transfer function:

Action diagram:

VAR_INPUT

VAR_INPUT
    fSetpointValue 	: REAL; (* setpoint value *)
    fActualValue 	: REAL; (* actual value *)
    bReset 		: BOOL;
    fCtrlCycleTime 	: REAL; (* controller cycle time in seconds [s] *)
    fKp 		: REAL; (* proportional gain Kp (P) *)
    fTn 		: REAL; (* integral gain Tn (I) [s] *)
    fTv 		: REAL; (* derivative gain Tv (D-T1) [s] *)
    fTd 		: REAL; (* derivative damping time Td (D-T1) [s] *)
END_VAR

fSetpointValue : Set point value of the controlled variable.

fActualValue : Actual value of the controlled variable.

bReset : TRUE at this input resets the internal state variables as well as the output of the controller.

fCtrlCycleTime : Controller cycle time for discrete-time implementation [s].

fKp : Proportional amplification

fTn : Integral-action time [s]

fTv : Derivative action time [s]

fTd : Damping time [s]

VAR_OUTPUT

VAR_OUTPUT
    fCtrlOutput 	: REAL;
    nErrorStatus	: UINT
END_VAR

fCtrlOutput : output of the PID element.

nErrorStatus : Provides the error number, if an error exists (nErrorStatus <> 0).

0 = nERR_NOERROR : no error.
1 = nERR_INVALIDPARAM : invalid parameter
2 = nERR_INVALIDCYCLETIME : Invalid cycle time

Development Environment | Target System | PLC Libraries to include
TwinCAT v2.8.0 Build > 747 TwinCAT v2.9.0 Build > 947 | PC (i386) | TcUtilities.Lib (Standard.Lib; TcBase.Lib; TcSystem.Lib are integrated automatically)
TwinCAT v2.7.0 Build > 522 TwinCAT v2.8.0 Build > 747 TwinCAT v2.9.0 Build > 947 | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


DT_TO_SYSTEMTIME

FUNCTION DT_TO_SYSTEMTIME

The "DT_TO_SYSTEMTIME" function allows a PLC variable in DATE_AND_TIME format (DT) to be converted to a Windows system time structure. The system time has a resolution of 1ms, while the resolution of DATE_AND_TIME is 1s. The "wMilliseconds" variable in the system time structure therefore always returns the value zero.

FUNCTION DT_TO_SYSTEMTIME : TIMESTRUCT

VAR_INPUT
    DTIN		: DT;
END_VAR

DTIN:: The date and time to be converted, in DATE_AND_TIME format.

Example of a call in FBD:

PROGRAM SystemTimeTest
VAR
    SystemTimeStruct  :TIMESTRUCT;
END_VAR

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


SYSTEMTIME_TO_DT

FUNCTION SYSTEMTIME_TO_DT

The "SYSTEMTIME_TO_DT" function allows the Windows system time structure to be converted to the DATE_AND_TIME format (DT) usual in a PLC. The system time has a resolution of 1ms, while the resolution of DATE_AND_TIME is 1s. The milliseconds from the system time are used in the course of the conversion to determine the direction of rounding for the returned DATE_AND_TIME value.

FUNCTION SYSTEMTIME_TO_DT : DT

VAR_INPUT
    TIMESTR		: TIMESTRUCT;
END_VAR

TIMESTR: The structure with the Windows system time requiring conversion.

Example of a call in FBD:

PROGRAM SystemTimeTest
VAR
    SystemTimeStruct  :TIMESTRUCT;
    DTFromSystemTime	:DT;
END_VAR

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


TIME_TO_OTSTRUCT

FUNCTION TIME_TO_OTSTRUCT

The "TIME_TO_OTSTRUCT" function allows a PLC variable in TIME format to be converted to a structure with milliseconds, seconds, minutes, hours, days and weeks.

FUNCTION TIME_TO_OTSTRUCT : OTSTRUCT

VAR_INPUT
    TIN		:TIME;
END_VAR

TIN: The value to be converted.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


OTSTRUCT_TO_TIME

FUNCTION OTSTRUCT_TO_TIME

The "OTSTRUCT_TO_TIME" function allows the structure with milliseconds, seconds, minutes, hours, days and weeks to be converted to the TIME format usual in a PLC.

FUNCTION OTSTRUCT_TO_TIME : TIME

VAR_INPUT
    OTIN		: OTSTRUCT;
END_VAR

OTIN: The value to be converted.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


SETBIT32

FUNCTION SETBIT32

The function sets the bit specified by a bit number in the 32 bit value that is passed to it and returns the resulting value.

FUNCTION SETBIT32 : DWORD

VAR_INPUT

VAR_INPUT
    inVal32			:DWORD;
    bitNo			:SINT;
END_VAR

inVal32: The 32-bit value that is to be modified.

bitNo: The number of the bit that is to be set (0-31). This number is internally converted to a modulo 32 value prior to execution.

Example of calling the function in FBD:

This sets bit 31 of the input value '0'. The result is the (hex) value '80000000'.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


CSETBIT32

FUNCTION CSETBIT32

The function sets/resets the bit specified by a bit number in the 32 bit value that is passed to it and returns the resulting value.

FUNCTION CSETBIT32 : DWORD

VAR_INPUT

VAR_INPUT
    inVal32			:DWORD;
    bitNo			:SINT;
    bitVal			:BOOL;
END_VAR

inVal32: The 32-bit value that is to be modified.

bitNo: The number of the bit that is to be set/reset (0-31). This number is internally converted to a modulo 32 value prior to execution.

bitVal: The new value of the set/reset bit (TRUE = 1, FALSE = 0);

Example of calling the function in FBD:

This sets bit 15 of the input value '16#8000000' to 1. The result is the (hex) value '80008000'.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


GETBIT32

FUNCTION GETBIT32

The function returns the status of the bit specified by a bit number in the 32 bit value that is passed to it as a boolean resulting value. The input value is not altered.

FUNCTION GETBIT32 : BOOL

VAR_INPUT

VAR_INPUT
    inVal32			:DWORD;
    bitNo			:SINT;
END_VAR

inVal32: The 32-bit value that is to be modified.

bitNo: The number of the bit that is to be set (0-31). This number is internally converted to a modulo 32 value prior to execution.

Example of calling the function in FBD:

Bit 2 in the input value '04' is interrogated here, and assigned to the boolean variable 'aGetBitResultVar'. When examined, it is found in this example to be 'TRUE'.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


CLEARBIT32

FUNCTION CLEARBIT32

The function resets the bit specified by a bit number in the 32 bit value that is passed to it to zero and returns the resulting value.

FUNCTION CLEARBIT32 : DWORD

VAR_INPUT

VAR_INPUT
    inVal32			:DWORD;
    bitNo			:SINT;
END_VAR

inVal32: The 32-bit value that is to be modified.

bitNo: The number of the bit that is to be set (0-31). This number is internally converted to a modulo 32 value prior to execution.

Example of calling the function in FBD:

This resets bit 31 of the input value 'C0000000'. The result is the (hex) value '40000000'.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


F_SwapReal

FUNCTION F_SwapReal

The way in which a REAL number is represented in the memory of a bus controller (165) is different from the way a REAL number is represented in the memory of an Intel system (PC). In order to represent a bus controller's REAL number correctly in a PC, it is necessary for the high and low words of the REAL number to be swapped. Under the programming environment this is already done in online or simulation mode. If it is desired to request the REAL data from a bus controller over the network (ADS protocol, ADSDLL, AdsOcx etc.) and to display it correctly in an Intel PC, then it is necessary to convert the REAL data into the correct format. This can either be done in the bus controller or in the PC. The F_SwapReal function can be used to convert the REAL variables (which might, for instance, be read by a VB application, or recorded with TwinCAT Scope View) into the correct format in an Intel PC. The fVal parameter that is passed is not affected by the conversion. The function returns a new REAL number with a modified representation in memory.

FUNCTION F_SwapReal : REAL

VAR_INPUT

VAR_INPUT
    fVal	:REAL;
END_VAR

fVal: The REAL value to be converted;

Example in ST:

PROGRAM MAIN
VAR
    Real_165 		: REAL;
    Real_i386 AT%MB0 	: REAL;
END_VAR

(* ADSREAD(.... ADR(Real_165), SIZEOF(Real_165)... );
...
...
...
*)
Real_i386 := F_SwapReal( Real_165 );
Real_i368 := Real_i368 + 0.001;

In the example, a 4-byte REAL variable in the bus controller is converted into the 4-byte REAL Intel format. The Real_i386 variable can, for instance, be correctly displayed on a VB form.

Development environment | Target System | PLC Libraries to include
TwinCAT v2.7.0 Build > 518 TwinCAT v2.8.0 Build > 735 | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


IsFinite

FUNCTION IsFinite

The function IsFinite() returns TRUE, if its argument has a finite value (INF < x < +INF). The function returns FALSE, if the argument is infinite or NaN (NaN = Not a number). IsFinite() checks whether the formatting of an LREAL or REAL variable complies with IEEE.

INF numbers may occur in a runtime system if the result of a mathematical operation falls outside the range that can be represented. E.g.:

PROGRAM MAIN
VAR
    fSingle : REAL := 12.34;
END_VAR
(*Cyclic called program code*)
fSingle := fSingle*2;

NaN numbers may occur in the runtime system if their actual formatting (memory content) was overwritten through illegal access (e.g. by using the MEMCPY of MEMSET functions). E.g.:

PROGRAM MAIN
VAR
    fSingle : REAL := 12.34;
END_VAR
(*Cyclic called program code*)
MEMSET( ADR( fSingle ), 16#FF, SIZEOF( fSingle ) ); (* Invalid initialization of REAL variable *)

Calling a conversion function with an NaN or INF number as parameter causes an FPU exception on a PC system (i368). This exception subsequently leads to the PLC being stopped. The function IsFinite() enables the value of the variables to be checked, and therefore the FPU exception to be avoided and program execution to be continued.

FUNCTION IsFinite : BOOL

VAR_INPUT
    x :T_Arg;
END_VAR

x: An auxiliary structure with information about the REAL or LREAL variables to be checked. The structure parameters have to be generated when IsFinite() is called from auxiliary functions F_REAL or F_LREAL and transferred as parameters.

Example of a call in ST:

In the following example, the formatting of a REAL and an LREAL variable is checked, and an FPU exception is avoided.

PROGRAM MAIN
VAR
    fSingle 		: REAL := 12.34;
    fDouble 		: LREAL := 56.78;
    singleAsString 	: STRING;
    doubleAsString 	: STRING;
END_VAR
fSingle := fSingle*2;
IF IsFinite( F_REAL( fSingle ) ) THEN
    singleAsString := REAL_TO_STRING( fSingle );
ELSE
    (* report error !*)
    fSingle := 12.34;
END_IF

fDouble := fDouble*2;
IF IsFinite( F_LREAL( fDouble ) ) THEN
    doubleAsString := LREAL_TO_STRING( fDouble );
ELSE
    (* report error !*)
    fDouble := 56.78;
END_IF

Important note:

In the following case, an FPU exception cannot be avoided through checking with IsFinite():

PROGRAM MAIN
VAR
    bigFloat : LREAL := 3.0E100;
    smallDigit: INT;
END_VAR
IF IsFinite( F_LREAL( bigFloat ) ) THEN
    smallDigit := LREAL_TO_INT( bigFloat );
END_IF

While the bigFloat variable has the right formatting, the variable value is too large for conversion into an INT type. An exception is triggered on a PC system (i368), and the runtime system is stopped.

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 Build > 522 TwinCAT v2.8.0 Build > 747 TwinCAT v2.9.0 Build > 947 | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


TYPE TIMESTRUCT

TYPE TIMESTRUCT:
STRUCT
   wYear            : WORD;
   wMonth           : WORD;
   wDayOfWeek       : WORD;
   wDay             : WORD;
   wHour            : WORD;
   wMinute          : WORD;
   wSecond          : WORD;
   wMilliseconds    : WORD;
END_STRUCT
END_TYPE

wYear : Specifies the year: 1970 ~ 2106;

wMonth : Specifies the month: 1 ~ 12 (January = 1, February = 2 and so on);

wDayOfWeek : Specifies the day of the week: 0 ~ 6 (Sunday = 0, Monday = 1 and so on );

wDay : Specifies the day of the month: 1 ~ 31;

wHour : Specifies the hour: 0 ~ 23;

wMinute : Specifies the minute: 0 ~ 59;

wSecond : Specifies the second: 0 ~ 59;

wMilliseconds : Specifies the millisecond: 0 ~ 999;

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


TYPE OTSTRUCT

TYPE OTSTRUCT
STRUCT
   wWeek		: WORD;
   wDay    	: WORD;
   wHour         	: WORD;
   wMinute       	: WORD;
   wSecond       	: WORD;
   wMilliseconds 	: WORD;
END_STRUCT
END_TYPE
Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 and above | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


TYPE T_Arg

TYPE T_Arg :
STRUCT
    eType	: E_ArgType	:= ARGTYPE_UNKNOWN;	(* Argument data type *)
    cbLen	: UDINT 		:= 0;			(* Argument data byte length *)
    pData	: UDINT 		:= 0;			(* Pointer to argument data *)
END_STRUCT
END_TYPE

eType : Argument data type;

cbLen : Argument data byte length;

pData : Pointer to argument data;

Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 Build > 522 TwinCAT v2.8.0 Build > 747 TwinCAT v2.9.0 Build > 947 | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


TYPE E_ArgType

TYPE E_ArgType :(

    ARGTYPE_UNKNOWN			:= 0,
    ARGTYPE_BYTE,
    ARGTYPE_WORD,
    ARGTYPE_DWORD,
    ARGTYPE_REAL,
    ARGTYPE_LREAL,
    ARGTYPE_SINT,
    ARGTYPE_INT,
    ARGTYPE_DINT,
    ARGTYPE_USINT,
    ARGTYPE_UINT,
    ARGTYPE_UDINT,
    ARGTYPE_STRING,
    ARGTYPE_BOOL,
    ARGTYPE_BIGTYPE
 );
END_TYPE
Development environment | Target system type | PLC libraries to include
TwinCAT v2.7.0 Build > 522 TwinCAT v2.8.0 Build > 747 TwinCAT v2.9.0 Build > 947 | BCxxxx (165) | Standard.Lb6, PlcSystemBC.Lb6, TcPlcUtilitiesBC.Lb6


F_REAL

Not supported for BCxxxx (165)