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

Address mapping

lukaszsz
2022-07-25
2022-07-25
  • lukaszsz - 2022-07-25

    Hi, I am a beginner at codesys and I have a simple question.
    How can I refer to a byte in a DWORD variable?

    For example:
    I have a dword variable "varD" and a byte variable "varB". I want to save varB variable to 3rd byte of varD. How to write it in codesys?

     
  • paulpotat

    paulpotat - 2022-07-25

    Hello,
    I would do this :

    varD := (varD AND 16#00FFFFFF) + SHL(TO_DWORD(varB), 3*8);
    

    However there might be better ways to do this, I'm not sure...

     
    • fajean - 2022-07-25

      I do not know whether the OP meant "3rd byte" as "last of 4" or "third of 4", but in the latter case, I think the mask should be "16#FF00FFFF" and the shift should be "2*8". I would probably use "OR" rather than "+", but I think in this case they are interchangeable.

       
      πŸ‘
      1

      Last edit: fajean 2022-07-25
  • lukaszsz - 2022-07-25

    It does not matter which byte it is exactly. I just wanted to know if there is any simple way such as by accessing a bit.
    That we enter the variable name, period and bit number.

    for example:
    varD.0: = true;

     
    • paulpotat

      paulpotat - 2022-07-25

      Well if you want something similar, you can create a union type like so :

      TYPE DWORD_BYTES :
      UNION
          value : DWORD;
          bytes : ARRAY[0..3] OF BYTE;
      END_UNION
      END_TYPE
      

      Then in your program you define varD as a DWORD_BYTES object and you can access its bytes like this :

      varD.bytes[byte_position] := varB;
      

      Where byte_position can be 0, 1, 2 or 3.
      And if you need to change varD value you can do this for example :

      varD.value := 16#FFFFFFFF;
      
       

Log in to post a comment.