你好,我正在尝试通过modbus rtu与arduino通信omron hmi。我只是在听arduino的数据,这样我就可以分析数据传输了。但是当我试图创建它的crc时,我无法获得corrrect数据。下面是算法和我编写的代码。如果有人知道这个问题,请帮帮我。
块引用的CRC-16计算示例一次在16位处理寄存器中处理1字节的消息,称为CRC寄存器。1在CRC寄存器中设置FFFF十六进制的默认值。2获取CRC寄存器的内容和消息的第一个字节的异或,并将结果返回CRC寄存器。3 CRC寄存器的内容向右移动1位,0放置在MSB中。4如果从LSB移位的位为0,则重复步骤3(即寄存器的内容被移动1位)。如果从LSB移出的位为1,则对CRC寄存器和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);
}
}
}发布于 2021-12-12 20:40:36
对于每一个字节的数据:
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;这就是全部。
https://stackoverflow.com/questions/70314390
复制相似问题