英文:
Multiplying time by integer in Codesys
问题
我想要将一个 TIME
变量乘以一个整数。文档 表示你可以使用 * 运算符与 TIME
变量相乘,但当我尝试以下操作时:
CYCLE_TIME : TIME := T#5MS;
CYCLE_TIME_OFFSET : TIME := CYCLE_TIME * 2;
或者
CYCLE_TIME : TIME := T#5MS;
CYCLE_TIME_OFFSET : TIME := CYCLE_TIME * TO_TIME(2);
或者
CYCLE_TIME : TIME := T#5MS;
CYCLE_TIME_OFFSET : TIME := (CYCLE_TIME * T#2MS);
我收到一个我不理解的错误:
我可以将时间与整数相乘吗?如果可以,应该如何操作?
英文:
I want to multiply a TIME
variable by an integer. Documentation says that you can use * with TIME
variables but when I try:
CYCLE_TIME : TIME := T#5MS;
CYCLE_TIME_OFFSET : TIME := CYCLE_TIME * 2;
Or
CYCLE_TIME : TIME := T#5MS;
CYCLE_TIME_OFFSET : TIME := CYCLE_TIME * TO_TIME(2);
Or
CYCLE_TIME : TIME := T#5MS;
CYCLE_TIME_OFFSET : TIME := (CYCLE_TIME * T#2MS);
I get an error I don't understand:
Can I multiply time by an integer, if so, how?
答案1
得分: 1
虽然 codesys 支持 TIME 的乘法运算,但奇怪的是它似乎不支持在编译时(在定义中)进行乘法运算。例如:
t1: TIME := T#5MS;
multiplier: UDINT := 2;
t2: TIME := t1 * multiplier;
会报错 C0073: Cannot multiply multiple operands of type 'TIME'
,而
t1: TIME := T#5MS;
multiplier: UDINT := 2;
t3: TIME := MUL(t1, multiplier);
会报错 C0007: Expression expected instead of 'MUL'
。
在运行时使用上述任何一种方法都能正常工作。
如果你绝对必须在定义阶段进行 TIME 的乘法运算,那么你可以将 TIME 强制转换为 UDINT/DWORD(TIME <=> UDINT/DWORD,其中 1 等于 1 毫秒,因此 12345 表示 12 秒和 345 毫秒),进行所需的操作,然后再将其转换回 TIME:
t6: TIME := UDINT_TO_TIME(TIME_TO_UDINT(t1) * multiplier);
英文:
While codesys does support TIME multiplication, strangely it seems to not support it at compile time (in the definition). For example:
t1: TIME := T#5MS;
multiplier: UDINT := 2;
t2: TIME := t1 * multiplier;
Gives C0073: Cannot multiply multiple operands of type 'TIME'
, while
t1: TIME := T#5MS;
multiplier: UDINT := 2;
t3: TIME := MUL(t1, multiplier);
Gives C0007: Expression expected instead of 'MUL'
.
Using any of the two above at runtime works as expected:
If you absolutely must multiply TIME in the definition phase, then you can always cast TIME to UDINT/DWORD (TIME <=> UDINT/DWORD, where 1 equals to 1 millisecond, so 12345 is 12 seconds and 345 milliseconds), do whatever operations you want, and then cast it back to TIME:
t6: TIME := UDINT_TO_TIME(TIME_TO_UDINT(t1) * multiplier);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论