Decoding 6-Bit Binary Position Input in TIA Portal for S7-1200

David Krause11 min read
SiemensTIA PortalTutorial / How-to
Licensed PE Working through this on a live machine? A Maine-licensed engineer can take it from here — included with IMD hardware, by the hour for everything else. Book an engineer

Problem Overview

Many indexing tables, rotary slides, linear transfer carriages, and tooling turrets accept a binary position selection where each bit of an input word represents a power of two. A drive or motion controller is then commanded to the position corresponding to the bit pattern. With 6 binary inputs (bit 0 through bit 5) the controller can select 2^6 = 64 unique positions (0 to 63, or 1 to 64 depending on numbering).

The PLC engineer needs to (a) read the 6 bits as a contiguous input word, (b) decode the bit pattern into a usable integer position, (c) hand the decoded value to the drive command path, and (d) validate that only one valid pattern is present. This article walks through every layer of that flow using TIA Portal V17 and later on S7-1200 (CPU 1211C / 1212C / 1214C / 1215C / 1217C) and S7-1500 CPUs. The same logic applies on S7-300 / S7-400 with minor syntactic adjustments.

Prerequisites

  • TIA Portal V17, V18, or V19 installed and licensed
  • S7-1200 CPU firmware V4.4 or higher (SCL operations below require this baseline)
  • S7-1500 CPU firmware V2.5 or higher if you target an S7-1500
  • STEP 7 Basic / Professional engineering license matching the CPU family
  • 6 wired digital inputs (24 V DC sourcing) addressed contiguously as a single input byte or word
  • Configured PROFINET or PROFIBUS connection to the drive or HMI
  • Read access to the Siemens Industry Online Support portal for the S7-1200 system manual and the TIA Portal programming and operating manual

Understanding Binary Position Encoding

A 6-bit position word uses the LSB (bit 0) as position 1 and the MSB (bit 5) as position 64. The integer value is the sum of 2^n for each set bit:

Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Decimal 1-Based Position
0 0 0 0 0 1 1 1
0 0 0 0 1 0 2 2
0 0 0 0 1 1 3 3
0 1 0 1 0 1 21 21
1 1 1 1 1 1 63 63
1 0 0 0 0 0 32 32

If your drive numbers positions 1 to 64 (1-based), the decoded integer plus one equals the position. If it numbers 0 to 63 (0-based), the decoded integer equals the position directly. Confirm which convention the drive expects before writing code; mismatches cause off-by-one errors that look like the drive is consistently one position short.

Reading the Input Word in TIA Portal

Wire the 6 selection inputs to 6 consecutive inputs on the S7-1200. For example, map them to I0.0 through I0.5 of the first DI module. TIA Portal lets you address them individually as %I0.0 through %I0.5, or as a packed input byte %IB0, or as a packed input word %IW0. The byte/word access is preferred for decode logic because it avoids 6 individual bit reads.

Create the following tag in the PLC tag table:

Name Type Address Comment
iPosRaw Word %IW0 Raw 6-bit position selection
iPosMask Word %MW10 Mask for lower 6 bits (16#003F)
iPosDecoded Int %MW12 Position 0 to 63
iPosCmd Int %MW14 Position 1 to 64 sent to drive
bPosValid Bool %M20.0 Exactly-one-bit diagnostic
Note: Input word %IW0 overlaps input byte %IB0 and %IB1. Address the lowest six bits of %IB0 to avoid crossing into the next byte, or shift and mask as shown in the SCL block below if wiring must use a non-aligned byte.

Method 1: Bit Mask + Comparator (Ladder Logic)

The original forum approach used an AND mask in MB10 to isolate the active bits. The corrected implementation compares the masked word to known constant patterns. Open a new Function Block (FB) called FB_PositionDecode and add the following network in LAD:

  1. Network 1 - Mask to 6 bits: Insert a MOVE box. Source: %IW0. Destination: %MW10. Then insert a WAND_W (Word AND Word). IN1: %MW10. IN2: 16#003F. OUT: %MW10. The mask 16#003F is binary 0000 0000 0011 1111, which keeps bits 0 to 5 and zeros bits 6 to 15.
  2. Network 2 - Cast to integer: Insert MOVE. IN: %MW10. OUT: %MW12. Because both tags are 16-bit, the bit pattern is preserved.
  3. Network 3 - Convert to 1-based position: Insert ADD_I. IN1: %MW12. IN2: 1. OUT: %MW14.
  4. Network 4 - Validity check: Insert a comparator network with one branch: %MW10 == 0 -> reset bPosValid; another branch: popcount (count of set bits) equals 1 -> set bPosValid. If you do not have a popcount instruction, use six explicit AND tests against the powers of two (W#16#0001, 0002, 0004, 0008, 0010, 0020) and OR the equality results.

This ladder implementation matches what the discussion described but adds the validity check the original approach skipped. Without that check, an input fault where two bits are set simultaneously will command the drive to an unintended intermediate position.

Method 2: Direct Integer Cast (SCL)

SCL on S7-1200 (firmware V4.4+) supports the cleanest solution. Open FB_PositionDecode, switch the editor to SCL, and write:

// Mask to 6 LSBs and decode to integer position
#iPosMask := #iPosRaw AND 16#003F;
#iPosDecoded := WORD_TO_INT(#iPosMask);
#iPosCmd := #iPosDecoded + 1;

// Validity: popcount must be exactly 1 and value <= 63
#bPosValid := FALSE;
IF (#iPosMask = 1) OR (#iPosMask = 2) OR (#iPosMask = 4) OR
   (#iPosMask = 8) OR (#iPosMask = 16) OR (#iPosMask = 32) THEN
    #bPosValid := TRUE;
END_IF;

// Saturate the command to safe bounds
IF #bPosValid = FALSE THEN
    #iPosCmd := 0;  // 0 used as "no command" sentinel
END_IF;

Call this FB from OB1 in a cyclic task. The WAND instruction in SCL on S7-1200 accepts the constant 16#003F directly because TIA Portal performs implicit WORD conversion. Refer to the TIA Portal programming reference for the operator precedence and the WORD_TO_INT behavior on the Siemens Industry Online Support portal.

Method 3: Decoder Instruction

TIA Portal exposes the legacy DECO (Decode) instruction that sets bit n of a target word based on the integer value at the input. This is the inverse operation and is useful for diagnostics (showing the active position bit on an HMI). Add this as a separate network:

// Show which input bit should be active based on commanded position
DECO(IN := #iPosDecoded, OUT := "DB_Diag".wActiveBit);

The instruction requires an input in the range 0 to 15, but you can split the decode into two DECO calls (one for the low byte, one for the high byte) if you need 64 discrete outputs for an LED tower or panel indicator.

Wiring and Signal Conditioning

Selection inputs typically originate from a BCD thumbwheel switch, a PLC-controlled output card, or a binary-coded selector. Observe the following rules when wiring to the S7-1200 SM 1221 DI:

  • Source-type wiring: 24 V from a clean supply to the selector, return to the DI channel.
  • Keep cable lengths under 30 m for unshielded, under 100 m for shielded. The S7-1200 system manual gives derating curves at S7-1200 product page.
  • Add a 100 ms input filter in the device configuration to reject contact bounce on mechanical selectors. This is configured per channel in the Properties dialog of the DI module.
  • Use opto-isolated intermediate relays if the selector is powered from a separate cabinet; do not tie grounds across cabinets without a reference equalizer.
  • For noisy environments, enable the hardware input filter to 1 ms or 3 ms even though it slows response - selection commands rarely need sub-millisecond latency.
Caution: Some S7-1200 firmware versions reset input image values on PROFIBUS-DP slave failure. Add a watchdog in the FB that holds the last valid position if iPosRaw stays at 0 for more than one scan cycle while bPosValid was previously true.

Drive Command Output Mapping

Once iPosCmd contains the integer position, send it to the drive. Three common patterns:

  1. PROFINET telegram with position number: Use the SINA_POS (Siemens POSitioning) or vendor-specific telegram. The decoded integer maps directly to slot 0 of the telegram.
  2. Analog output to drive: If the drive expects 0 to 10 V mapped to 0 to 63 positions, scale with NORM_X and SCALE_X: NORM_X(VALUE := iPosCmd, MIN := 0, MAX := 63, OUT := rNorm); then SCALE_X(VALUE := rNorm, MIN := 0, MAX := 27648, OUT := %QW64);
  3. Binary output to drive discrete inputs: Write iPosDecoded to an output word %QW64. The drive reads its own discrete inputs to command position.

Always clamp the command before sending. A raw value of 65 would command an out-of-range position. Add the following saturation block to the FB output:

IF #iPosCmd > 64 THEN
    #iPosCmd := 64;
END_IF;
IF #iPosCmd < 1 THEN
    #iPosCmd := 1;  // or 0 for "no command"
END_IF;

HMI Integration

On a WinCC Comfort or Unified Panel, bind the HMI tag to iPosCmd in the PLC tag table. Configure the field as a numeric I/O field with limits 1 to 64 and add a status indicator bound to bPosValid. For operator feedback, mirror the decoded integer back as discrete outputs using the DECO instruction in Method 3 so the operator sees which input bit is currently active.

If you are using TIA Portal's Unified HMI, use the HMIRuntime namespace in a JavaScript action to read iPosCmd and display the active bit pattern.

Verification and Commissioning

Walk through these steps after downloading the project to the PLC:

  1. Open the watch table and force iPosRaw to 16#0001. Verify iPosCmd = 2 and bPosValid = TRUE.
  2. Force iPosRaw to 16#0003 (bits 0 and 1 set). Verify bPosValid = FALSE and iPosCmd = 0.
  3. Force iPosRaw to 16#0040 (bit 6 set, outside the 6-bit range). Verify iPosCmd = 0 after the mask zeros bit 6.
  4. Force iPosRaw to 16#0020 (bit 5 set, position 32). Verify iPosCmd = 33 (1-based).
  5. Cycle power on the CPU. Confirm that the decoded position restarts at 0 and the drive does not jog.
  6. Connect the HMI and verify the displayed value matches the input word.
  7. With the drive enabled, command each of the 64 positions in sequence and verify mechanical alignment.

Troubleshooting Matrix

Symptom Likely Cause Diagnostic Fix
Drive always commands position 1 Selector common not wired; floating inputs read as 0 Force each input from the watch table and verify voltage with a meter Wire selector common to 24 V reference of the DI module
Position is off by one 1-based vs 0-based mismatch Compare drive doc with FB output Adjust the ADD_I constant or remove the +1
Drive jogs unexpectedly Multiple bits set during selector transition Monitor bPosValid in the trace Add 100 ms input filter; gate iPosCmd on bPosValid
Decoded value stuck at 0 iPosRaw input byte address wrong Watch table forces iPosRaw and reads back Recheck module slot and offset
High bits (6 to 15) bleed into command Mask constant wrong Inspect iPosMask in watch table Verify mask is 16#003F, not 16#3F00
SCL compile error: type mismatch iPosMask declared as INT, result is WORD Inspect tag type Use WORD_TO_INT before assignment
DECO output all bits set Input value out of range 0 to 15 Watch DECO IN Split decode; clamp to 0 to 15 before call
HMI shows --- PLC tag connection lost Diagnostics in TIA Portal online view Re-establish HMI connection; verify PLC IP

Edge Cases and Field-Proven Caveats

Selectors with mechanical detents generate transient bit patterns during rotation. A selector moving from position 32 to position 33 will briefly pass through patterns where bits 0, 1, and 5 are simultaneously high. Without the bPosValid gate, the drive receives a position 35 command for one or two scan cycles. This is the most common cause of unexplained slide motion on commissioning day. The gate must be in the same OB cycle as the decode; do not move it to a separate background OB.

If the system uses an HMI to display the position, consider writing the bPosValid status to a diagnostic byte that the HMI can show as a banner ("Invalid Position"). Operators will recognize the fault much faster than they will recognize a wrong number on the screen.

Watch the PLC cycle time when scaling to an analog output. NORM_X and SCALE_X add roughly 5 microseconds each on an S7-1214C. If your OB1 cycle is already tight, move the scaling to a slower cyclic interrupt OB (e.g., OB35 at 100 ms).

For S7-1500 users, replace WAND_W with the typed operator AND in SCL because the S7-1500 instruction set is typed. The SCL block above works on both families but the instruction comments differ.

Summary

What TIA Portal instruction reads a packed input word from 6 selection inputs?

Use %IW0 (input word) or %IB0 (input byte) in the PLC tag table. Address the lowest 6 bits to keep the read aligned. If the inputs land on different bytes, read %IB0 and %IB1 separately, then OR them with a shift.

How do I mask only the lower 6 bits of a 16-bit word in TIA Portal?

In SCL, use iPosMask := iPosRaw AND 16#003F;. In LAD/FBD, insert a WAND_W (Word AND Word) box with IN1 tied to the source word and IN2 tied to the constant W#16#003F. The constant 16#003F is binary 0000 0000 0011 1111 and clears bits 6 to 15.

Why does my drive command the wrong position when the selector is moving?

Mechanical selectors pass through transient bit patterns during rotation. Without a one-bit-set validity check (bPosValid), the FB passes these transient values to the drive. Add a 100 ms input filter on the DI module and gate the position command on a popcount-of-one condition.

Can I use this 6-bit decode pattern on an S7-1500 or S7-300?

Yes. The SCL code in Method 2 works on S7-1500 firmware V2.5+ and on S7-300 / S7-400 with minor syntax adjustments. Replace WAND_W in ladder with the typed AND instruction and verify the WORD_TO_INT instruction is licensed on the CPU.

Do I add 1 to the decoded integer for the position command?

Only if your drive uses 1-based numbering (1 to 64). Most drives that accept binary position selection use 0-based numbering (0 to 63). Confirm with the drive manual; mismatches cause an off-by-one error where the slide consistently arrives one position short.

Back to blog