DINT adds 2 additional empty bytes in array/union

drled
2021-10-07
2021-10-12
  • drled - 2021-10-07

    Hi,

    I'm relatively new to the codesys platform.

    I'm creating an interface by using a union.
    Everything works fine, except when start adding a DINT variable (int, word etc is working fine).

    When monitoring "online", it seems that right before the DINT there are added 2 empty bytes for no reason?
    Can someone explain this behaviour?

    TYPE stMyTestStructure :
    STRUCT
    
    //structure of 8 bytes
    
        bByte0      : BYTE; // byte 0
        bByte1      : BYTE; //byte 1
        diTestDINT  : DINT; //byte 2,3,4 & 5 32 Bit = 4 bytes
        bByte2      : BYTE; //byte 6
        bByte3      : BYTE; //byte 7
    
    END_STRUCT
    END_TYPE
    
    TYPE uMyTestUnion :
    UNION
        data    : stMyTestStructure;
        aData   : ARRAY[0..7] OF BYTE;
    END_UNION
    END_TYPE
    

     

    Last edit: drled 2021-10-07
  • TimvH

    TimvH - 2021-10-08

    Probably pack mode 4 is used on your controller. You can add an "attribute" to the structure with e.g. pack mode 0 and it then probably works as you expect. See https://help.codesys.com/webapp/_cds_pragma_attribute_pack_mode;product=codesys;version=3.5.17.0 for more information.

     
    πŸ‘
    2
    • Ingo

      Ingo - 2021-10-08

      I can agree with Tim. This is the problem. But when changing the pack mode, your program will not work on all controllers. For instance, when you have an ARM CPU, with a bit bad luck at the way the memory is connected, it is likely, that your DINT will not be correctly copied, when the memory is not aligned. So I really can't recommend to use this pragma, if you don't know exactly what you are doing.

      I think you can say, that only in two cases, this is no problem:

      • you access the memory only with SysMemCpy()
      • your application has to run only on a specific controller, and you proved, that it works on this one.
       
  • drled - 2021-10-12

    The problem was solved by setting {attribute 'pack_mode' := '1'}
    Thanks!

     

Log in to post a comment.