Matlab中的CRC 16 [英] CRC 16 in matlab

查看:907
本文介绍了Matlab中的CRC 16的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上想在Matlab中为Modbus协议生成crc,并且我已经在matlab中使用了以下代码.我还给了消息数组message=uint16([hex2dec('01') hex2dec('02') hex2dec('00') hex2dec('C4') hex2dec('00') hex2dec('16')]);,并在最后以0xffff完成了bitand运算,但是它无法给出正确的crc ..

i actually want to generate crc in matlab for Modbus protocol and i have used following code in matlab. I have also given message array as message=uint16([hex2dec('01') hex2dec('02') hex2dec('00') hex2dec('C4') hex2dec('00') hex2dec('16')]); and done bitand with 0xffff at the end, but it is unable to give correct crc..

我的代码如下,根据Modbus crc计算器,预期的crc为 B839 ,但是给出的是 B8DD (十进制47325).如果代码中有任何更改,请帮助我.谢谢.

My code is as below and the expected crc is B839 as per the Modbus crc calculator but it is giving B8DD(47325 decimal). Please help me if there is anything to change in the code. Thank you.

function crc_val = crc3 (~)
crc = uint16(hex2dec('1D0F'));  % Non-augmented initial value equivalent to augmented initial value 0xFFFF
polynomial = hex2dec('1021'); % Polynomial
message=uint16([hex2dec('01') hex2dec('02') hex2dec('00') hex2dec('C4') hex2dec('00') hex2dec('16') hex2dec('00') hex2dec('00')]);
for i = 1:(length(message)-2) % Not taking the last 2 bytes because they are the CRC.
    crc = bitxor(crc, bitsll(message(i), 8));
    for j = 1:8
        if (bitand(crc, hex2dec('8000')) > 0);
            crc = bitxor(bitsll(crc, 1), polynomial);
        else
            crc = bitsll(crc, 1);
        end
    end
end
crc_val = bitand(crc, hex2dec('ffff'));

end

推荐答案

您尝试.它可以作为BSD许可证使用.您将不会遇到任何许可问题.以下内容说明 CRC 的实际工作方式. 以下也有助于理解该概念.

Did you try this. It is available as BSD license. You would not face any possible licensing issues. The following explains how CRC actually works. The following also helps understand the concept.

%usage:  crc16(input vector).

//

function [resto] = crc16(h)
    % g(X) =  X^16+X^15+X^2+1
    gx = [1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1];
    % P(X) is given input vector
    px = h;
    %Calculate P(x)x^r
    pxr=[px zeros(1,length(gx)-1)];
    % deconvolve  (r), entre pxr y gx
    [c r]=deconv(pxr,gx);

    r=mod(abs(r),2);
    % returncrc-16
    resto=r(length(px)+1:end);
end

这篇关于Matlab中的CRC 16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆