函数代码
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)
计算原理(步骤)
- Load a 16–bit register with FFFF hex (all 1’s). Call this the CRC register.
- 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. - Shift the CRC register one bit to the right (toward the LSB), zero–filling the MSB. Extract and examine the LSB.
- (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). - Repeat Steps 3 and 4 until 8 shifts have been performed. When this is done, a complete 8–bit byte will have been
processed. - Repeat Steps 2 through 5 for the next 8–bit byte of the message. Continue doing this until all bytes have been processed.
- The final content of the CRC register is the CRC value.
- When the CRC is placed into the message, its upper and lower bytes must be swapped as described below.