Workaround to use variable in Bit addressing

Hello, after understanding that it is not possible to use a variable in bit addressing, I am wondering if there are any possible workarounds to still dynamically access elements of an UDINT.

And are there any plans to implement this feature natively into AS?

You can use this Code-Example to use it direct in your Program or to Create a Library-Function.

The Mask can be set in Code in Various Numeric-Systems (see List below), and will select the Bits Used for the Output.

Hex: MaskUDINT := 16#01;
Binary: MaskUDINT := 2#0000_0000_0000_0000_0000_0000_0000_0001
Dezimal: MaskUDINT := 1;

BY Bitnumber 0…31: MaskUDINT := SHL(1,Number);

ST-Code:

VAR
	ValueUDINT : UDINT;
	MaskUDINT : UDINT;
	ValueBOOL : BOOL;
END_VAR

PROGRAM _INIT
	 
	MaskUDINT := 16#01; 
	
END_PROGRAM

PROGRAM _CYCLIC
	
	ValueBOOL := UDINT_TO_BOOL(ValueUDINT AND MaskUDINT);
	 
END_PROGRAM

Hello Tim,

Not sure if that is what you want to do but you could let the PLC processor take care of the conversion directly.

For that, you will need a DWord variable to be able to use your variable in bit addressing. For your specific case, the UDINT variable needs to be created as a pointer.

With this variable declared as a pointer you would normally access another variable of UDINT datatype. In that case we are going to “cheat” and access our DWORD variable from which we can perform bit addressing.

IMPORTANT: Be aware that both variables must match in size (4 bytes in the previous case) or you will be writting outside the designated memory area.

Hey, Thanks for your Answer. But I don’t think that completely fits my use case here.
My initial goal was to iterate over the single Bits of an UDINT and check if it changed.

Probably “BIT_TST” would be suitable for you

GuID 40885fb5-c6a1-4e60-be1f-9dc9a82a1bfa

4 Likes

If you want to have the Information which Bits in an UDINT have changed it depends on the way you want to have the Data-Output formated how to do it.

ChangedBitsUDINT := OldUDINT XOR NewUDINT;

ChangedBits will have TRUE Values for all Bits which were in Old and New different, for all Bits were Old and New is same it will be FALSE

image

If you would like as an Output an Array of Bools you have to use the Mask variant and a Loop to check each single Bit and set the Array Output.

I tried Michales first approach and Olivers suggestion.

I would say they both do what I asked for, to dynamically access separate Bits of a UDINT. So I will mark this question as solved.

I found out that this dynamic approach doesn’t work for my use case but that is not part of the question.

2 Likes

Just so anyone who finds this post in the future has it, here is a link to the online Help for the GUID that Oliver references above:
B&R Online Help (br-automation.com)