Modbus Function Code 22 (0x16): Mask Write Register Specification & Hex Guide

Industrial VFDs, motor protection relays, and multi-channel PLC modules frequently pack 16 independent control flags—Run, Reverse, Jog, Fault Reset, Remote Enable—into a single 16-bit Holding Register (4xxxx). Using Function Code 06 (Write Single Register) requires reading the register first, toggling a bit in client software, and writing all 16 bits back—creating a dangerous race condition if another HMI or controller writes to an adjacent bit in between.

The official Modbus Application Protocol Specification V1.1b3 solves this with Function Code 22 (0x16 in hex) — Mask Write Register. FC 22 performs an atomic read-modify-write directly inside the server/slave using two 16-bit masks: And_Mask and Or_Mask. This engineering guide breaks down the bitwise math, hex PDU layouts, exception codes, Python pymodbus usage, and simulation testing with ModbusSimulator.

1. The Bit-Masking Formula & Truth Table

Upon receiving a valid FC 22 request, the Modbus server applies the following bitwise equation to the target Holding Register:

Result = (Current_Contents AND And_Mask) OR (Or_Mask AND (NOT And_Mask))

Notice how clean this rule is in practice:

  • If bit n of And_Mask = 1: The existing bit n in the register is preserved unchanged (Or_Mask bit n is ignored because NOT 1 = 0).
  • If bit n of And_Mask = 0: The existing bit n is cleared and replaced by bit n of Or_Mask.
Desired Action on Bit n And_Mask Bit Or_Mask Bit Resulting Register Bit
Leave unchanged (Preserve) 1 0 or 1 Original bit value
Force bit to 1 (Set) 0 1 1
Force bit to 0 (Clear) 0 0 0

2. Request & Response Hex Frame Analysis

Suppose Holding Register 40005 (wire address 0x0004) currently holds 0x0012 (binary 0000 0000 0001 0010). We want to set bit 0 to 1 and clear bit 1 to 0, while leaving bits 2–15 untouched:

  • And_Mask = 1111 1111 1111 1100 = 0xFFFC
  • Or_Mask = 0000 0000 0000 0001 = 0x0001
  • Result = (0x0012 & 0xFFFC) | (0x0001 & 0x0003) = 0x0010 | 0x0001 = 0x0011

Modbus RTU Request Frame (Slave ID 1)

[Slave] [FC] [Addr Hi Lo] [And_Mask] [Or_Mask] [CRC-16]
  01     16    00 04        FF FC      00 01     8E 32

Modbus TCP ADU Frame (Unit ID 1, Transaction 0x0001)

[TxID] [Proto] [Len] [Unit] [FC] [Addr] [And] [Or]
00 01   00 00  00 08   01    16  00 04  FF FC 00 01

Normal Response Frame

A compliant Modbus server simulator or PLC echoes the exact request PDU (Address, And_Mask, and Or_Mask) back to the master:

01 16 00 04 FF FC 00 01 [CRC-16]

3. Standard Exception Codes for FC 22

Exception Code Name Root Cause in FC 22
0x01 Illegal Function Device firmware does not implement Function Code 22 (common on minimal low-cost sensors).
0x02 Illegal Data Address Target reference address is outside mapped Holding Register range or is read-only.
0x03 Illegal Data Value Malformed PDU length (must be exactly 7 PDU bytes: FC + 2-byte addr + 2-byte And + 2-byte Or).
0x04 Server Device Failure Internal EEPROM/flash write failure or hardware interlock rejected the mask update.

4. Python Implementation Using Pymodbus

from pymodbus.client import ModbusTcpClient

def mask_write_control_word(host="127.0.0.1", port=502, unit_id=1):
    client = ModbusTcpClient(host, port=port)
    client.connect()

    # Target wire address 4 (40005): preserve bits 2..15, clear bit 1, set bit 0
    response = client.mask_write_register(
        address=4,
        and_mask=0xFFFC,
        or_mask=0x0001,
        slave=unit_id,
    )

    if response.isError():
        print(f"FC 22 failed: {response}")
    else:
        print(f"Mask write echoed: addr={response.address}, and=0x{response.and_mask:04X}, or=0x{response.or_mask:04X}")

    client.close()

if __name__ == "__main__":
    mask_write_control_word()

5. Testing FC 22 Bit Masks with ModbusSimulator

Before writing control words to live motor drives or switchgear, verify your bit masks safely using ModbusSimulator (our Windows Modbus emulator & Modbus TCP simulator):

  • Spin up a virtual Modbus slave simulator on port 502 or a virtual COM pair.
  • View holding register values in binary (16-bit flag view) and hexadecimal simultaneously.
  • Inspect raw incoming and outgoing byte traffic in the protocol log to verify And_Mask and Or_Mask endianness.
  • Compare FC 22 atomic writes against FC 16 (Write Multiple Registers) and FC 23.

Test Modbus TCP & RTU Bit Masks Without Hardware

Download ModbusSimulator for Windows — unified Master + Slave simulator with live binary register views and raw packet logging.

Download Free 30-Day Trial

Frequently Asked Questions

What is Modbus Function Code 22 (0x16)?

Function Code 22 is Mask Write Register. It lets a client set or clear individual bits inside a 16-bit Holding Register atomically using an AND mask and an OR mask.

What is the bit-masking formula for FC 22?

Result = (Current AND And_Mask) OR (Or_Mask AND (NOT And_Mask)). Bits set to 1 in And_Mask keep their current value; bits set to 0 take the corresponding bit from Or_Mask.

Why use FC 22 instead of FC 06?

FC 06 overwrites all 16 bits, forcing clients to read-modify-write and risking race conditions when multiple HMIs share one status/control word. FC 22 updates target bits atomically in one transaction.

Does FC 22 work on Input Registers (3xxxx)?

No. Input Registers are read-only per the Modbus specification. FC 22 only operates on Holding Registers (4xxxx).

Can I test FC 22 using ModbusSimulator?

Yes. ModbusSimulator lets you inspect live binary/hex register values and test Modbus TCP and RTU request/response frames on Windows without physical PLCs.