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 is a read/modify/write operation, and uses 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'. They could, however, 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 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 parameter is the AND value to use in the mask write operation. The valid range is 0–65535. The orMask parameter is the OR value to use in the mask write operation. The valid range is 0–65535.

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

andMask = 6
orMask = 0

maskWrite(m,20,andMask,orMask)