Implementing a Checksum algorithm as Embedded Matlab Function

조회 수: 31(최근 30일)
Ashwin
Ashwin 2015년 5월 4일
댓글: Jan 2021년 10월 2일
Hello,
I have been trying implement a checksum algorithm. I have implmeneted a matlab function that converts the inputs to binary and then performs some bit-wise operations to compute the checksum. Unfortunately, this does not work as an embedded matlab function because of several reasons: 1) some functions including dec2bin, num2str, int2bin etc.. cannot be compiled 2) MxArray is not supported
The function I have coded is as follows. Is there anyway I can get these functions to compile or another way to perform functions such as the int2bin function. Thank you in advance for your help and suggestions.
function [chec , intcheck] = checksum (torque, extc, messageCntr)
% create dataArray for checksum from inputs
if (torque < 0)
pos_torque = abs(torque);
p = fliplr (bitget(bitcmp(uint16(pos_torque)), 1:16))
p = num2str(p)
char1 = dec2bin(bin2dec(p)+bin2dec('0000000000000001'))
torque_fin = char1-'0';
else
torque_fin = fliplr(bitget(torque, 1:16));
end
byte_0=torque_fin(1:8);
byte_1=torque_fin(9:16);
byte_2=zeros(1,8);
byte_3=zeros(1,8);
byte_4=zeros(1,8);
byte_5=zeros(1,8);
bits_extc = fliplr(bitget(extc, 1:4));
bits_messageCntr = fliplr(bitget(messageCntr, 1:4));
byte_6 = [bits_extc, bits_messageCntr];
dataArray = [byte_0, byte_1, byte_2, byte_3, byte_4, byte_5, byte_6];
% checksum
%initialization
dataLength= 6;
startValue = [0,0,0,1,1,0,1,1]; % 1B
genPol = [1,0,0,1,1,0,1,1]; %9B
finalXor = [1,1,1,1,1,1,1,1]; %FF
byteCount =0;
bitCount = 0;
chec = 0;
chec = startValue;
for byteCount = 0:dataLength
chec = bitxor(dataArray (byteCount*8+1: (byteCount*8 +8)), chec);
%C = dataArray (byteCount*8+1: (byteCount*8 +8))
D = chec
for bitCount=1:8
if (chec(1) ~= 0)
chec = bitxor([chec(2:8),0], genPol);
else
chec = [chec(2:8),0];
end
end
end
chec = bitxor(chec, finalXor);
intcheck = bin2dec(num2str(chec));
end

답변(1개)

Sriram Narayanan
Sriram Narayanan 2015년 5월 6일
I simplified your code to not include the condition for negative torque (which could be implemented using Simulink blocks) and I was able to calculate the correct checksum. Please note that functions like "num2str" cannot be compiled and therefore, need to be declared as extrinsic functions using the coder.extrinsic keyword. Only thing that you have to ensure is that the outputs to your function have their sizes pre-defined using a pre-initialization.
More information about this function is below:
Please find the working model which consists of the MATLAB function block attached.
  댓글 수: 2
Jan
Jan 2021년 10월 2일
@NGR MNFD: Please do not attach a new question as a comment to an answer of another question. Create a new question instead. Thanks.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by