MATLAB Answers

Implementing a Checksum algorithm as Embedded Matlab Function

27 views (last 30 days)
Ashwin on 4 May 2015
Answered: Sriram Narayanan on 6 May 2015
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';
torque_fin = fliplr(bitget(torque, 1:16));
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
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);
chec = [chec(2:8),0];
chec = bitxor(chec, finalXor);
intcheck = bin2dec(num2str(chec));

Answers (1)

Sriram Narayanan
Sriram Narayanan on 6 May 2015
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.


Community Treasure Hunt

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

Start Hunting!