How to access data at the bit level in Sysmac
It is quite common that it is necessary to either read or write a single bit as part of a BYTE/WORD/DWORD/LWORD in Sysmac. In Sysmac it is not possible to directly enter the address of the bit you wish to access. Instead there are two main methods you may use to accomplish bit access.
1. Union
A union allows you to create multiple members of a variable that share the same memory. You can take advantage of this to create a variable that is directly accessible at various data type levels including the bit level. We would recommend the union method for scalable solutions where you often need to read or write bits in a byte.
For this example we will create a byte array where each byte is accessible at the bit level.
- Create the union. As we are accessing a byte the bit array must be of length 8.
- Create the variable. In this example we are creating the data as an array of length 10. You can also use this same method for standard non-indexed variables.
- Add the variable to your ladder code. In this example we are reading from byte 3, bit 4 and writing to byte 5, bit 2 of MyData.
2. Function Block
There are a few functions in Sysmac that allow you to interact with data at the bit level. We would suggest using the functions when you need to have a one off instance of accessing a byte at the bit level.
Functions of note:
- TestABit - Outputs the value of the specified bit.
- OutABit - Sets the specified bit to True or False.
- SetABit - Sets the specified bit to True.
- ResetABit - Sets the specified bit to False.
- MoveBit - Copies a bit from one variable to another.
In this example we will cover TestAbit and OutABit with a byte array.
- Create the byte array. You can also use this same method for standard non-indexed variables.
- Write the ladder code. In this example we are reading from byte 3, bit 4 and writing to byte 5, bit 2 of MyData.