Sample: Digital IO access

This example illustrates how you can access the real-time environment of a TwinCAT system via Modbus.

The Modbus server's standard mapping maps the digital outputs (coils) to the process image of the PLC's physical outputs.

PROGRAM MAIN
VAR
  Q00 AT%QX0.0  : BOOL;
  Q01 AT%QX0.1  : BOOL;
  Q02 AT%QX0.2  : BOOL;
  Q03 AT%QX0.3  : BOOL;
  Q04 AT%QX0.4  : BOOL;
  Q05 AT%QX0.5  : BOOL;
  Q06 AT%QX0.6  : BOOL;
  Q07 AT%QX0.7  : BOOL;

  fbWriteCoils  : FB_MBWriteCoils;
  bWrite        : BOOL;
  nValue        : INT;
END_VAR


IF NOT bWrite THEN
  nValue := nValue + 1;

  bWrite :=  TRUE;

  fbWriteCoils.nQuantity := 8;
  fbWriteCoils.cbLength  := SIZEOF(nValue);
  fbWriteCoils.pSrcAddr  := ADR(nValue);
  fbWriteCoils.tTimeout  := T#5s;
  fbWriteCoils(bExecute:=TRUE);

ELSIF NOT fbWriteCoils.bBUSY THEN
    bWrite := FALSE;
END_IF
  fbWriteCoils(bExecute:=FALSE);


After a rising edge on bWrite, the running light is written to the PLC's physical output area (Q00-Q07).

The bit order is set as follows:

Bit

8 MSB

7

6

5

4

3

2

1 LSB

Output

7

6

5

4

3

2

1

0

MSB = Most significant bit

LSB = Least significant bit

Requirements

Development environment

Target platform

PLC libraries to include

TwinCAT v3.1.0

IPC or CX (x86, x64, ARM®)

Tc2_ModbusSrv