在Codesys中将时间乘以整数

huangapple go评论64阅读模式
英文:

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);

我收到一个我不理解的错误:

在Codesys中将时间乘以整数

我可以将时间与整数相乘吗?如果可以,应该如何操作?

英文:

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:

在Codesys中将时间乘以整数

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 &#39;TIME&#39;, while

t1: TIME := T#5MS;
multiplier: UDINT := 2;
t3: TIME := MUL(t1, multiplier);

Gives C0007: Expression expected instead of &#39;MUL&#39;.

Using any of the two above at runtime works as expected:

在Codesys中将时间乘以整数

在Codesys中将时间乘以整数

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);

在Codesys中将时间乘以整数

huangapple
  • 本文由 发表于 2023年7月3日 19:13:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604199.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定