如何在结构化文本中将枚举转换为 uint
How to cast enum to uint in structured text
我在 codesys 3.5 中有一个结构化文本程序 运行,我想在其中将某些电机的模式设置为多个值。为了拥有良好的封装代码,我定义了以下结构:
{attribute 'strict'}
TYPE PD4_modes :
(
no_mode := 0,
position:= 1,
velocity := 2,
homing_mode := 3
) UINT;
END_TYPE
然而,一旦我尝试将此值分配给驱动电机模式的适当变量(sint
):
mot1_ctrmode = PD4_modes.homing_mode
我收到错误:type PD4_modes cannot be cast to sint
。这是为什么?我以为我在结构中将模式定义为 uint?因此不需要铸造,对吧?我还尝试删除属性 strict
但这没有帮助...
您需要将枚举转换为 SINT。
例如:
//Shorter way:
mot1_ctrmode := TO_SINT(PD4_modes.homing_mode);
//Typical way
mot1_ctrmode := UINT_TO_SINT(PD4_modes.homing_mode);
如果可能,您还可以考虑将枚举定义为 SINT 或将 mot1_ctrmode 定义为 UINT。所以不需要类型转换。
首先,SINT
和UINT
不一样:
- SINT: Small(有符号)INT, 8 位, (-128到 127)
- UINT:Unsigned INT,16 位,(0 到 65535)
它们是完全不同的整数类型。如果需要,您可以将一个转换为另一个(只要数字适合另一种类型,否则您可能会丢失一些数据)。 Already showed that, but in short, you can use the UINT_TO_SINT
function. Another option is to use a UNION.
但是,如果可以,您应该尝试更改一个或另一个的类型以匹配相同的类型,或者更好的是,您可以将 mot1_ctrmode
定义为 PD4_modes
并让编译器为你做那个工作。如果 mot1_ctrmode
和 PD4_modes
的类型匹配,您将避免从 ENUM 转换为原始整数。
如果你想避免从原始整数转换为 ENUM,那么你必须删除 strict attribute(用 {attribute 'strict'}
做 PD4_modes_enum_variable := mot1_ctrmode;
会得到 C0358: 'mot1_ctrmode' is not a valid value for strict ENUM type 'PD4_modes'
错误),或者像我之前提到的那样使用 UNION。
我在 codesys 3.5 中有一个结构化文本程序 运行,我想在其中将某些电机的模式设置为多个值。为了拥有良好的封装代码,我定义了以下结构:
{attribute 'strict'}
TYPE PD4_modes :
(
no_mode := 0,
position:= 1,
velocity := 2,
homing_mode := 3
) UINT;
END_TYPE
然而,一旦我尝试将此值分配给驱动电机模式的适当变量(sint
):
mot1_ctrmode = PD4_modes.homing_mode
我收到错误:type PD4_modes cannot be cast to sint
。这是为什么?我以为我在结构中将模式定义为 uint?因此不需要铸造,对吧?我还尝试删除属性 strict
但这没有帮助...
您需要将枚举转换为 SINT。 例如:
//Shorter way:
mot1_ctrmode := TO_SINT(PD4_modes.homing_mode);
//Typical way
mot1_ctrmode := UINT_TO_SINT(PD4_modes.homing_mode);
如果可能,您还可以考虑将枚举定义为 SINT 或将 mot1_ctrmode 定义为 UINT。所以不需要类型转换。
首先,SINT
和UINT
不一样:
- SINT: Small(有符号)INT, 8 位, (-128到 127)
- UINT:Unsigned INT,16 位,(0 到 65535)
它们是完全不同的整数类型。如果需要,您可以将一个转换为另一个(只要数字适合另一种类型,否则您可能会丢失一些数据)。 UINT_TO_SINT
function. Another option is to use a UNION.
但是,如果可以,您应该尝试更改一个或另一个的类型以匹配相同的类型,或者更好的是,您可以将 mot1_ctrmode
定义为 PD4_modes
并让编译器为你做那个工作。如果 mot1_ctrmode
和 PD4_modes
的类型匹配,您将避免从 ENUM 转换为原始整数。
如果你想避免从原始整数转换为 ENUM,那么你必须删除 strict attribute(用 {attribute 'strict'}
做 PD4_modes_enum_variable := mot1_ctrmode;
会得到 C0358: 'mot1_ctrmode' is not a valid value for strict ENUM type 'PD4_modes'
错误),或者像我之前提到的那样使用 UNION。