KL6781 with CX5120

This example describes how a simple PLC program for M-Bus can be written in TwinCAT and how it is linked with the hardware. The task is to read a counter with four digital inputs.

Example: MBus_Sample_KL6781_CX5120.zip

Hardware

Setting up the components

The following hardware is required:

Set up the hardware and the M-Bus components as described in the associated documentation.

This example assumes that the counter address is known.

Software

Creation of the PLC program

Create a new "TwinCAT XAE project" and a "Standard PLC project".

Add the library Tc2_MBus under References in the PLC project.

Generate a Global Variable List with the name GVL_MBus and create the following variables:

VAR_GLOBAL
    stComIn    AT %I* : ST_KL6781inData22B;
    stComOut   AT %Q* : ST_KL6781outData22B;
    stCom             : ST_MBUS_Communication;
END_VAR

stComIn: Input variable for the M-Bus terminal (see ST_KL6781inData22B).

stComOut: Output variable for the M-Bus terminal (see ST_KL6781outData22B)

stCom: Required for the communication with M-Bus (see ST_MBUS_Communication).

Create a program (CFC) for the background communication with M-Bus. The FB_MBUSKL6781 block is called in this program. Make sure to link the communication block with stComIn, stComOut and stCom.

KL6781 with CX5120 1:

Create a MAIN program (CFC) in which the block FB_MBUS_REL_PadIn4 is called up. Link the input usiAddress of the counter block with the local variable usiAddress and stCom with the global variable stCom.

KL6781 with CX5120 2:

Navigate to the task configuration section and configure the PlcTask. By way of example, the task is assigned priority 16 and a cycle time of 6 ms.

KL6781 with CX5120 3:

Create a further task for the background communication. Assign a higher priority (smaller number) and a lower interval time to this task than the PLCTask.

KL6781 with CX5120 4:

Add the program for the communication to this task. Further information on task configuration can be found in the description of the function block FB_MBUSKL6781.

KL6781 with CX5120 5:

I/O configuration

Select the CX as target system and initiate a search for its hardware. In the project instance within the PLC section, you can see that the input and output variables are assigned to the corresponding tasks.

KL6781 with CX5120 6:

Now link the global variables of PLC program with the inputs and outputs of the Bus Terminals. Create the Solution and enable the configuration.

When linking the data array, make sure that you select both the All types and Continuous options.
Use the Shift key and the right mouse button to mark all data bytes of the terminal.

KL6781 with CX5120 7:

After starting the PLC, the current values are regularly read by the counter.