我无法用arduino创建正确的omron-hmi crc代码



你好,我正试图通过modbus rtu与omron hmi进行通信。实际上,我只是在用arduino听数据,这样我就可以分析数据传输了。但当我试图创建它的crc时,我无法获得正确的crc数据。下面是我写的算法和代码。如果有人知道这个问题,请帮帮我。

区块报价CRC-16计算示例消息在一个称为CRC寄存器的16位处理寄存器中一次处理1个字节。

1在CRC寄存器中设置FFFF十六进制的默认值。

2对CRC寄存器的内容和消息的第一个字节进行XOR结果返回到CRC寄存器。

3 CRC寄存器的内容向右移动1位,0位于MSB中。

4如果从LSB移位的位为0,则重复步骤3(即,移位寄存器的内容1个比特(。如果从LSB移位的位是1,则对CRC寄存器的内容进行XOR,并且A001十六进制,结果返回到CRC寄存器。

5重复步骤3和4,直到寄存器的内容向右移动了8位。

6如果尚未到达消息的末尾,则对消息和CRC寄存器,结果返回到CRC寄存器,过程为从步骤3开始重复。

7结果(CRC寄存器中的值(位于消息的较低字节中。追加结果示例如果计算的CRC值是1234十六进制,则如下所述将其附加到命令帧中。

crc=0xFFFF;  //A default value of FFFF hex is set in the CRC register.
LSB=0; 
cnt=0;


Serial.print("CRC-");
Serial.println(crc,BIN);
for(i=0;i<13;i++)
{
//An XOR is taken of the contents of the CRC register and the first byte of the message, and the
//result is returned to the CRC register.
//If the end of the message has not been reached, an XOR is taken of the next byte of the
//message and the CRC register, the result is returned to the CRC register, and the procedure is
//repeated from step 3.
crc=crc^data[i]; 
LSB=crc&1;
cnt=0;
while(cnt<8)       //Steps 3 and 4 are repeated until the contents of the register have been shifted 8 bits to the right.
{
crc=crc>>1;             //The contents of the CRC register is shifted 1 bit to the right, and 0 is placed in the MSB.
crc=crc&0x7fff;
cnt++;

//LSBe=LSB;
LSB=crc&1;
if(cnt==8)break;
Serial.print("LSB-");
Serial.println(LSB,HEX);

// If the bit shifted from the LSB is 0, step 3 is repeated (i.e., the contents of the register is shifted 1 more bit).
//If the bit shifted from the LSB is 1, an XOR is taken of the contents of the CRC register and
//A001 hex, and the result is returned to the CRC register.
if(LSB==0)
{
crc=crc>>1;
crc=crc&0x7fff;
cnt++;
Serial.print("CRC2-");
Serial.println(crc,BIN);
}
else if(LSB==1)
{
crc=crc^operation;
Serial.print("CRC3-");
Serial.println(crc,BIN);
}
}
}

对于每个字节的数据:

crc ^= data[i];
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;

仅此而已。

最新更新