首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我不能用arduino创建正确的omron hmi crc代码

我不能用arduino创建正确的omron hmi crc代码
EN

Stack Overflow用户
提问于 2021-12-11 10:33:20
回答 1查看 76关注 0票数 -1

你好,我正在尝试通过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十六进制,则追加结果的示例如下所示。

代码语言:javascript
复制
 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);
    }
  }
 }
EN

回答 1

Stack Overflow用户

发布于 2021-12-12 20:40:36

对于每一个字节的数据:

代码语言:javascript
复制
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;

这就是全部。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70314390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档