ModPackQTModPackQT
Node-RED ExamplesResourcesSign up
HomeResourcesNode-RED ExamplesMask Write Register (FC22) — Set/Clear Individual Bits
WritesNode-RED Modbus Example

Mask Write Register (FC22) — Set/Clear Individual Bits

FC22 lets you flip individual bits in a holding register without disturbing the rest. Useful for enabling/disabling specific modes in a control word without reading first. The formula is: result = (current AND andMask) OR (orMask AND NOT andMask).

What you need

  • Node-RED v3+
  • node-red-contrib-modbus installed
  • Device that supports FC22 (not all do — check the datasheet)

Flow Overview


Current register value: 0b0000000000001001  (bits 0 and 3 set)

AND mask: 0xFFFF  (keep everything)
OR  mask: 0x0004  (set bit 2)

Result:   0b0000000000001101  (bits 0, 2, and 3 now set)

To CLEAR bit 3:  AND mask = 0xFFF7, OR mask = 0x0000

Node-RED Flow JSON

Node-RED Flow JSON
[
  {"id":"inj10","type":"inject","name":"Set bit 2","once":true,"wires":[["fn10"]],"x":120,"y":1000},
  {"id":"fn10","type":"function","name":"Build FC22 payload","func":"// Set bit 2 (mask 0x0004), preserve all other bits
const AND_MASK = 0xFFFF;  // keep all other bits
const OR_MASK  = 0x0004;  // set bit 2
msg.payload = { value: [AND_MASK, OR_MASK], address: 5, quantity: 1, unitid: 1, fc: 22 };
return msg;","wires":[["req10"]],"x":330,"y":1000},
  {"id":"req10","type":"modbus-flex-write","name":"FC22 Mask Write","server":"srv1","wires":[["dbg12"],[]],"x":550,"y":1000},
  {"id":"dbg12","type":"debug","name":"FC22 result","active":true,"wires":[],"x":750,"y":1000},
  {"id":"srv1","type":"modbus-client","name":"My Slave","clienttype":"tcp","tcpHost":"192.168.1.100","tcpPort":502,"unit_id":1}
]

To import: open Node-RED → Hamburger menu → Import → paste this JSON → Deploy.

Expected Output

// Before:  register 5 = 0x0009 (bits 0 and 3)
// After:   register 5 = 0x000D (bits 0, 2, and 3)

Common Gotchas

  • Not all Modbus devices support FC22 — if unsupported you'll get exception 01 (Illegal Function).
  • To SET a bit: AND mask = 0xFFFF, OR mask = bit position (e.g. 0x0004 for bit 2).
  • To CLEAR a bit: AND mask = ~bit (e.g. 0xFFFB for bit 2), OR mask = 0x0000.
  • The node expects value as an array of two integers: [andMask, orMask].
  • If you need to both set and clear in one operation, combine: AND mask clears unwanted bits, OR mask sets desired bits.

Same in ModPackQT — in 30 seconds

ModPackQT exposes FC22 in the advanced write menu. Enter the AND and OR masks in the dialog — no function node JavaScript needed.

Was this example helpful?

More Writes examples

All Node-RED Modbus Examples (30)

ModPackQT · Node-RED Modbus Examples · Updated 2026