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
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