I made union, which allow me to use same data as REAL or 4 bytes (Module in profibus device has 4 BYTE registers to write REAL floating point type value).
The union:
TYPE U_4Bytes2Real :
UNION
abDataBytes : ARRAY[0..3] OF BYTE;
rDataFloat : REAL;
END_UNION
END_TYPE
When I want to get access to this variable like REAL, I write:
U_4Bytes2Real.rDataFloat
When I want to get access to this variable like 4 BYTE ARRAY, I write:
U_4Bytes2Real.abDataBytes
I want to have a function, which gets REAL value, and inside it, I want to write it to the registers as an ARRAY of BYTES.
How to tell my function, that argument is REAL?
I' using function like that:
bFunResult := F_SetMod22(bDataGroup := 3, bChannel := 3, bDataFloat := 20.0, nTimeout := 100);
and i get error
Cannot convert type 'LREAL' to type 'U_4Bytes2Real'
Do I have to convert it INTO function, or there is some method to use union in function argument?
CodePudding user response:
Answer
UNION is a STRUCT with a shared dataspace
This means anything that you can do with a STRUCT, you can do with a UNION. Whether that is use for inputs/outputs to a method, function, function block.
VAR
Data : U_4Bytes2Real;
END_VAR
F_Function( RealValue := Data.rDataFloat );
Example
Very simplest program to demonstrate this principle. It doesn't matter whether you are using a UNION or a STRUCT, they are accessed exactly the same.
TYPE st_Struct :
STRUCT
Value : REAL;
Packed : ARRAY [ 0..3 ] OF BYTE;
END_STRUCT
END_TYPE
TYPE u_Union :
UNION
Value : REAL;
Packed : ARRAY[0..3] OF BYTE;
END_UNION
END_TYPE
FUNCTION f_Sum : REAL
VAR_INPUT
A, B : REAL;
END_VAR
f_Sum := A B;
PROGRAM MAIN
VAR
Str : st_Struct;
Uni : u_Union;
Result : REAL;
END_VAR
Result := f_Sum( Str.Value, Uni.Value );
CodePudding user response:
For this answer I assume from your incomplete information:
Declaration assumption:
VAR
bFunResult : U_4Bytes2Real;
METHOD F_SetMod22 : LREAL
Then you can write:
bFunResult.rDataFloat = TO_REAL(F_SetMod22(...));
And later use:
bFunResult.abDataBytes
BUT !!!:
Be aware, that TO_REAL will cut off information if the returned LREAL does not fit into a REAL.