%-- Conv. Encoder --%
clc
clear all
%-- 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

%-- Building the block --%
k=3;
r=1/2;
R=1/r;
g1=[1 1 1];
g2=[1 0 1];
g=[g1;g2];

%-- Encoding --%
E=zeros(1,R*n);
s=zeros(1,k);
for t=1:n
    M=m(1,t);
    s(1,k)=M;
     %-- get the generation formula --%
    for i=1:R
        z=g(i,:);
        %-- select the bits connected to XOR --%
        d=1;
        for j=1:k
            if z(1,j)==1
                o(1,d)=s(j);
                d=d+1;
            end
        end
        %-- XOR operation --%
        p=o(1,1);
        for h=2:d-1
            p=xor(p,o(1,h));
        end
        %-- save the result in serial --%
        T=i+(t-1)*R;
        P=p;
        E(1,T)=P;
    end
    for f=1:k-1
        s(1,f)=s(1,f+1);
    end
end
%-- Interface with serial port--%
prt = serial('COM1');   
set(prt,'BaudRate',9600);
fopen(prt);
fwrite(prt,m);
fclose(prt);   
Er=zeros(1,2*n);

%-- 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

     

