top of page
Search
Writer's pictureIvaylo Fiziev

Practical use case: Bit to Byte conversion

Updated: Jan 31

I got some requests for this type of conversion recently so I decided to make a post out of it. The logic is quite straight-forward but still it will be nice to have an example. The idea is to convert a number of bits to a single BYTE, WORD, DWORD etc. value. On turn the value will be assigned to a signal or used by another SCL block. To implement this all we need is a SCL block that takes individual bits on input and provides the value on output. For this we rely on bit indexers. This is stateless logic so it is better to implement it as a function:

FUNCTION "BitToByte" : BYTE
VERSION:1.0
VAR_INPUT
	bit1 : BOOL;
	bit2 : BOOL;
	bit3 : BOOL;
	bit4 : BOOL;
	bit5 : BOOL;
	bit6 : BOOL;
	bit7 : BOOL;
	bit8 : BOOL;
END_VAR
BEGIN
	#BitToByte.%X0 := #bit1; 		// set bit 1
	#BitToByte.%X1 := #bit2;		// set bit 2
	#BitToByte.%X2 := #bit3;		// set bit 3
	#BitToByte.%X3 := #bit4;		// set bit 4
	#BitToByte.%X4 := #bit5;		// set bit 5
	#BitToByte.%X5 := #bit6;		// set bit 6
	#BitToByte.%X6 := #bit7;		// set bit 7
	#BitToByte.%X7 := #bit8;		// set bit 8
END_FUNCTION

Save this block to a UTF-8 encoded BitToByte.scl file and put it in the SCL vault.

In your main block you can call the function like this:

FUNCTION_BLOCK "MAIN"
VERSION:1.0
VAR_INPUT
	bit1 : BOOL;
	bit2 : BOOL;
	bit3 : BOOL;
	bit4 : BOOL;
	bit5 : BOOL;
	bit6 : BOOL;
	bit7 : BOOL;
	bit8 : BOOL;
END_VAR
VAR_OUTPUT
	out : BYTE;
END_VAR
BEGIN
#out := "BitToByte"(bit1:=#bit1, bit2:=#bit2, 
	bit3:=#bit3, bit4:=#bit4, 
	bit5:=#bit5, bit6:=#bit6, 
	bit7:=#bit7, bit8:=#bit8);
END_FUNCTION_BLOCK

Once you wire the inputs and outputs you can check the behavior in simulation panel:

You can extend this example so it works for WORD and DWORD as well. You can also try to do the opposite (ByteToBit) conversion. This time the function will have one input and eight outputs. The logic inside the function should be reversed.

Note: There are customers that would like to see the values in simulation panel in hexadecimal or binary format. Unfortunately SCL cannot help with that. The user interface should be enhanced to do so.


See you in the next one.


37 views0 comments

Comentarios

Obtuvo 0 de 5 estrellas.
Aún no hay calificaciones

Agrega una calificación
bottom of page