%-- CRC Code --%
clc
clear all
%-- CRC generation polynomial --%
g = [1,1,1,0,1,1,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0];
sg = size(g);
G = sg(1,2);

%-- Generate the message --%
n=300;
r=rand(1,n);
for i=1:n
    if r(i)>=0.5
        m(i)=1;
    else
        m(i)=0;
    end
end
%-- CRC Block --%
s = zeros(1,G);
for i = 1 : n;
    s(1,1) = xor ( m(1,i) , s(1,G-1) );
    for j = 2 : G
        if g(1,j) == 0
            s(1,j) = s(1,j-1);
        else
            s(1,j) = xor ( s(1,j-1) , m (1,i) );
        end
    end
end
OUT = [m,s];

%-- Interface with serial port--%
Er=zeros(1,2*n);
prt = serial('COM1');   
set(prt,'BaudRate',9600,'parity','even');
fopen(prt);
fwrite(prt,m);
fclose(prt);   

%-- Comparing the results--%
test=bitxor(E,Er);
NOE=0;
L=1;
for i=1:2*n
    if test(1,i)==1
        NOE=NOE+1;
        LOE(1,L)=i;
        L=L+1;
    end
end

