计算Modbus报文CRC的Matlab程序

计算Modbus报文CRC的Matlab程序

函数代码

function crc = crc_modbus(frame)
%%
% frame由Slave Adress. Function Code以及Data组成,格式为[xx;xx;xx;...]% xx由十六进制表示,含2个字节。
% 输出格式: crc = [CRC Lo; CRC Hi], [xx; xx]%%初始化
frame_dec = hex2dec(frame);
frame_bin = dec2bin(frame_dec, 16); % 将十六进制转变为二进制
initial_crc = uint8(ones(1, 16)); % CRC初始值0xFFFF
op_crc = uint8([1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1]);% 0xA001,用于异或运算
%% 利用for循环计算二进制表示的CRC
[n, ~] = size(frame);
for i = 1:n
    frame_bin_element = frame_bin(i, :);
    frame_bin_element =  frame_bin_element';
    frame_bin_element_dec = bin2dec(frame_bin_element);
    frame_bin_element_dec = frame_bin_element_dec';
    frame_crc =  uint8(frame_bin_element_dec);
    if i == 1
        crc = bitxor(initial_crc, frame_crc);
    else
        crc = bitxor (crc, frame_crc);
    end
    LSB = crc(16);
    for j = 1:8
        crc = [uint8(0), crc(1:15)];
        if LSB == 1
            crc = bitxor(crc, op_crc);
        end
        LSB = crc(16);
    end
end
%% 将二进制CRC转变为十六进制
crc_bin = dec2bin(crc);
crc_dec = bin2dec(crc_bin');
crc = dec2hex(crc_dec , 4);
crc = [crc(3:4);crc(1:2)]; % [CRC Lo; CRC Hi]
end

计算方法参考资料

MODBUS over serial line specification and implementation guide V1.02 (http://www.modbus.org
计算原理(步骤)

  1. Load a 16–bit register with FFFF hex (all 1’s). Call this the CRC register.
  2. Exclusive OR the first 8–bit byte of the message with the low–order byte of the 16–bit CRC register, putting the result in the
    CRC register.
  3. Shift the CRC register one bit to the right (toward the LSB), zero–filling the MSB. Extract and examine the LSB.
  4. (If the LSB was 0): Repeat Step 3 (another shift).
    (If the LSB was 1): Exclusive OR the CRC register with the polynomial value 0xA001 (1010 0000 0000 0001).
  5. Repeat Steps 3 and 4 until 8 shifts have been performed. When this is done, a complete 8–bit byte will have been
    processed.
  6. Repeat Steps 2 through 5 for the next 8–bit byte of the message. Continue doing this until all bytes have been processed.
  7. The final content of the CRC register is the CRC value.
  8. When the CRC is placed into the message, its upper and lower bytes must be swapped as described below.
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值