VAR_INPUT
value : DWord; // tag where the bit states has to be counted
numberOfBits : USInt; // number of bits in input tag "value", in case of Byte=8, Word=16, Dword=32
END_VAR
VAR_OUTPUT
countBitsFalse : USInt; // number of bits are false in input tag
countBitsTrue : USInt; // number of bits are true in input tag
END_VAR
VAR_TEMP
tempBinaryValues : DWord; // temp tag to store and work on the input value
tempLoopIndex : DInt; // temp tag for iterating trough tag via loop
tempCountBitsTrue : USInt; // temp tag to count bits are true
tempCountBitsFalse : USInt; // temp tag to count bits are false
END_VAR
VAR CONSTANT
//常数.主要方便程序阅读
ZERO : USInt := 0; // numeric zero used for initialization
INCREMENT : USInt := 1; // numeric one to increment counters
SHIFT_ON_BIT_RIGHT : USInt := 1; // numeric one to shift bits one position to the right
START_INDEX : DInt := 1; // start index for FOR loop is one, because of the given number of bits
END_VAR
REGION Logic
// init counter tags 初始化参数
#tempCountBitsFalse := #ZERO;
#tempCountBitsTrue := #ZERO;
#tempBinaryValues := #value;
// iterate over input tag 迭代输入标签
FOR #tempLoopIndex := #START_INDEX TO USINT_TO_DINT(#numberOfBits) DO
// check if bit is true or false 检查位为ON还是OFF
IF #tempBinaryValues.%X0 THEN
#tempCountBitsTrue += #INCREMENT;
ELSE
#tempCountBitsFalse += #INCREMENT;
END_IF;
// shift input tag one to the right 右移一位
#tempBinaryValues := SHR(IN := #tempBinaryValues, N := #SHIFT_ON_BIT_RIGHT);
END_FOR;
// set output values 输出处理
#countBitsFalse := #tempCountBitsFalse;
#countBitsTrue := #tempCountBitsTrue;
// no error handling needed
ENO := TRUE;
END_REGION
仿真调试:
仔细观察哦.
P.S.
右移指令帮助文档
SHR | :右移 |
---|
说明
使用“右移”指令,可以将参数 IN 的内容逐位向右移动,并将结果作为函数值返回。参数 N 用于指定应将特定值移位的位数。
如果参数 N 的值为“0”,则将参数 IN 的值作为结果。
如果参数 N 的值大于可用位数,则参数 IN 的值将向右移动该位数个位置。
无符号值移位时,用零填充操作数左侧区域中空出的位。如果指定值有符号,则用符号位的信号状态填充空出的位。
下图说明了如何将整型操作数的内容向右移动 4 位:
参数
下表列出了该指令的参数:
参数 | 声明 | 数据类型 | 存储区 | 说明 | |
---|---|---|---|---|---|
S7-1200 | S7-1500 | ||||
IN | Input | 位字符串、整数 | 位字符串、整数 | I、Q、M、D、L | 要移位的值 |
N | Input | USINT、UINT、UDINT | USINT、UINT、UDINT、ULINT | I、Q、M、D、L | 对值 (IN) 进行移位的位数 |
函数值 | 位字符串、整数 | 位字符串、整数 | I、Q、M、D、L | 指令的结果 |
有关有效数据类型的更多信息,请参见“另请参见”。
示例
以下示例说明了该指令的工作原理:
SCL |
---|
"Tag_Result" := SHR(IN := "Tag_Value",N := "Tag_Number"); |
下表将通过具体的操作数值对该指令的工作原理进行说明:
参数 | 操作数 | 值 |
---|---|---|
IN | Tag_Value | 0011 1111 1010 1111 |
N | Tag_Number | 3 |
函数值 | Tag_Result | 0000 0111 1111 0101 |
将“Tag_Value”操作数的内容向右移动 3 位。该指令的结果作为函数值在“Tag_Result”操作数中返回。