Welcome to our new forum
All users of the legacy CODESYS Forums, please create a new account at account.codesys.com. But make sure to use the same E-Mail address as in the old Forum. Then your posts will be matched. Close

How to convert 2 word into float - MODBUS

adamsmith
2020-08-15
2020-08-17
  • adamsmith - 2020-08-15

    Hello,

    I am new to the programming PLC field.

    I am using TwinCat 2 (very similar to Codesys).

    I am trying to read the floating variable via MODBUS RTU.
    The read variables are in a word array. How can i convert 2 word into float/real?
    Moreover I need to swap order of these words.

    I know that I can do it via memory allocations but there is too many variables.

    Thank for help.

     
  • aliazzz

    aliazzz - 2020-08-15

    Hi,

    Maybe you should try to search this forum for "word to real".
    There are more then several postings on this specific problem.

    Good luck ;-)

    https://forge.codesys.com/forge/talk/search/?q=word+to+real

     

    Last edit: aliazzz 2020-08-15
  • S1ack

    S1ack - 2020-08-17

    I do this quite a bit. I use a union, and the ROL function depending on endianness.

    The union. I called it 'TypeCast' because that was the equivalent function in LabVIEW.

    TYPE TypeCastDWReal :
    UNION
        dw  :   DWORD;
        rl  :   REAL;
    END_UNION
    END_TYPE
    

    Then I have two function that use the union depending on the direction you want the conversion done.

    FUNCTION TCRealSwapped : REAL
    VAR_INPUT
        dw  :   DWORD;
    END_VAR
    VAR
        MyUnion :   TypeCastDWReal;
    END_VAR
    
    MyUnion.dw := ROL(dw,16);       //  Word swap dword input because it's big endian on ModbusTCP
    TCRealSwapped := MyUnion.rl;    //  Function (via union) returns real
    
    FUNCTION TCDWordSwapped : DWORD
    VAR_INPUT
        rl  :   REAL;
    END_VAR
    VAR
        MyUnion :   TypeCastDWReal;
    END_VAR
    
    MyUnion.rl  :=  rl;                         //  Input to function is REAL
    TCDWordSwapped  := ROL(MyUnion.dw,16);      //  Function returns DWORD, needs word swap for ModbusTCP register space
    

    Then I step through the modbus data array via pointer and byte offset, and pass the dwords/reals into the function block.

    This is reading a real input to my server.

    pDword  :=  ADR(awEMS) + 12;    dsEMS.i.rRealPowerDemandkW          :=  TCRealSwapped(pDword^); 
    

    This is writing real into the data array outbound on my client...

    pDWord  :=  ADR(awEMS) + 2014;  pDWord^ :=  TCDWordSwapped(dsEMS.q.rRatedACVoltage);
    
     
    • aliazzz

      aliazzz - 2020-08-17

      UNION is not supported in CODESYS v23 (TwinCAT2).

       

Log in to post a comment.