Main Content

Modify the Contents of a Holding Register Using a Mask Write

You can modify the contents of a holding register using the maskWrite function. The function can set or clear individual bits in a specific holding register. It performs a read/modify/write operation, using a combination of an AND mask, an OR mask, and the current contents of the register.

The function algorithm works as follows:

 Result = (register value AND andMask) OR (orMask AND (NOT andMask))

For example:

                 Hex    Binary
Current contents  12   0001 0010
And_Mask          F2   1111 0010
Or_Mask           25   0010 0101
(NOT And_Mask)    0D   0000 1101
                  --   ----------
Result            17   0001 0111

If the orMask value is 0, the result is simply the logical ANDing of the current contents and the andMask. If the andMask value is 0, the result is equal to the orMask value.

The contents of the register can be read by using the read function with the target set to 'holdingregs'. However, the contents values could be changed subsequently as the controller scans its user logic program.

The syntax for the mask write operation for holding registers is:

maskWrite(obj, address, andMask, orMask)

If you want to designate a server ID, use:

maskWrite(obj, address, andMask, orMask, serverId)

The obj parameter is the name of the Modbus object. The following examples assume you have created a Modbus object, m. For information on creating the object, see Create a Modbus Connection.

The address is the register address to perform mask write on. The andMask argument is the AND value to use in the mask write operation. The valid range is 0–65535. The orMask argument is the OR value to use in the mask write operation. The valid range is 0–65535.

This example establishes bit 0 at address 20, and performs a mask write operation. Because the andMask is 6, that clears all bits except for bits 1 and 2, which are preserved.

andMask = 6
orMask = 0
maskWrite(m,20,andMask,orMask)