ModSlaveSim help v3.04 - 4.4.9. Handling Control/Status Flags in Holding/Input registers
Download manual: HTML
Many devices use individual bits as control or status flags. A Modbus master may access these flags using the coil and discrete functions, which are specifically intended for bit handling, or it may access them in groups of 16 or 32 using the holding register and input register functions. ModSlaveSim can handle them either as 1-bit Discrete Inputs/Coils, or as 1-bit flags in groups of 16 or 32 (i.e. as int16 or int32 values). If your slave device does not provide Discrete Inputs/Coils, then programming of the registers requires the bit manipulation techniques described below.
Bit manipulation in ModSlaveSim is done using the shift and bit operators, in the same way as it is done in programming languages such as C and Java. If you are not familiar with the bit-manipulation techniques used in these languages, you may find the following "idioms" useful.
You can create a mask for a bit using the left-shift operator. For example, you could use "1 << 5" as a mask for bit 5 (which is the 6th bit from the right, since bits are numbered from 0).
You can test whether a bit is set using the "&" operator. For example:
if $123 & (1 << 5) != 0 then ...
tests whether bit 5 of register 123 is set.
You can set a bit using the "|" operator. If the statement:
if $25 > 0 then $123 | (1 << 5)
is associated with register 123, then it will set bit 5 of that register if the value of register 25 is greater than 0. If you were to use the "^" operator instead of "|", this statement would toggle bit 5 instead of setting it (i.e. it would set it if it was originally clear, and clear it if it was originally set).
To clear a bit, you need a combination of the "&" and "~" operators. For example, the following statement (if associated with register 123):
if $25 > 0 then $123 & ~(1 << 5)
will clear bit 5 of register 123 if register 25 is greater than 0.
These idioms can be extended to handle groups of bits simultaneously, by using a mask with more than one bit set. For example, the expression "$123 & 12 != 0" (or equivalently, "$123 & (1 << 3 | 1 << 2) != 0") could be used to test whether bit 2 or bit 3 of register 123 is set.