Integration into TwinCAT (BC9191)
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.
Hardware
Setting up the components
The following hardware is required:
- 1x Bus Terminal Controller BC9191
- 1x potential feed terminal 24V DC
- 1x M-Bus master terminal KL6781
- 1x end terminal KL9010
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 PLC project for BC-based systems (BCxx50 via AMS) and add the library TcMBus.lbx. Then navigate to Project→Options... →Build and select TreatLREAL as REAL.

Next, generate the following global 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.
stComOut: Output variable for the M-Bus terminal.
stCom: Required for communication with M-Bus.
Since BC devices can only process one task, communication with M-Bus cannot run separately.
Therefore, create a MAIN program (CFC) in which the FB_MBUSKL6781() and FB_MBUS_REL_PadIn4() function blocks are called. Make sure to link the communication block with stComIn, stComOut and stCom.

Link the input usiAddress of the counter block with the local variable usiAddress and stCom with the global variable stCom.

Go to the task configuration and give the task a lower interval time. More detailed information can be found in the FB_MBUSKL6781() block description.

Now load the project as a boot project to the BC and save it.
Configuration in the System Manager
Create a new TwinCAT System Manager project, select the BC as the target system, and search for the associated hardware.
Add the PLC program created above under PLC configuration.

Now link the global variables of the PLC program with the Bus Terminal inputs and outputs, create the allocations, and activate the configuration. Then start the device in run mode.
Your BC is now ready for use.
After starting the PLC, the current values are regularly read by the counter.