Search code examples
castingcodesysstructured-text

How to cast enum to uint in structured text


I have a structured text program running in codesys 3.5, in which I want to set the mode of some motor to several values. In order to have good encapsulated code I defined the following struct:

{attribute 'strict'}
TYPE PD4_modes :
(
    no_mode := 0,
    position:= 1,
    velocity := 2,
    homing_mode := 3
) UINT;
END_TYPE

However as soon as I try to assign this value to the appropriate variable (an sint) which drives the motor mode as so:

mot1_ctrmode = PD4_modes.homing_mode

I get the error: type PD4_modes cannot be cast to sint. Why is that? I thought I defined the modes as uint in the struct? Therefore no casting should be necessary right? I also tried to erase the attribute strict but that did not help...


Solution

  • First of all, SINT is not the same as UINT:

    • SINT: Small (signed) INT, 8 bits, (-128 to 127)
    • UINT: Unsigned INT, 16 bits, (0 to 65535)

    They are completely different integer types. If you want, you can cast one into another (as long as the number fits in the other type, otherwise you may loose some data). Quirzo Already showed that, but in short, you can use the UINT_TO_SINT function. Another option is to use a UNION.

    However, if you can, you should try changing the type of one or the other to match the same, or better yet, you could define mot1_ctrmode to be PD4_modes and let the compiler do that work for you. If the types of mot1_ctrmode and PD4_modes match, you will avoid casting from an ENUM to raw integer.

    If you want to avoid casting from a raw integer to an ENUM, then you have to either remove the strict attribute (doing PD4_modes_enum_variable := mot1_ctrmode; with {attribute 'strict'} will give C0358: 'mot1_ctrmode' is not a valid value for strict ENUM type 'PD4_modes' error), or use a UNION as I mentioned previousely.