%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                              Example 4.9                                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                         %
%                   Succesive Approximation Converter                     %
%                                                                         %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clear all;

%-------------------------------------------------------------------------%
%                         Simulation parameters                           %
%-------------------------------------------------------------------------%

nbit=8;                     % 8-bits ADC
nbin=2^nbit-1;
points=nbin*50;
t=[1:points];

%-------------------------------------------------------------------------%
%                         Input signal                                    %
%-------------------------------------------------------------------------%

ampl=1;
in_offset=0.0001;
full_scale=1;

    x=(ampl*t)/points+in_offset+0.001*rand(1,points);

%-------------------------------------------------------------------------%
%                          DAC characteristics                            %
%-------------------------------------------------------------------------%

offset=0; 
dnl=0/2^nbit; 
firstbin=0;  
lastbin=full_scale;
yd=statchar(nbin+1,offset,dnl,firstbin,lastbin,0);

%-------------------------------------------------------------------------%
%                              Distortion                                 %
%-------------------------------------------------------------------------%

sec=0.005; 
third=0.005; 
fourth=0; 
fifth=0;
yDAC = dist(yd,sec,third,fourth,fifth);

%-------------------------------------------------------------------------%
%                          SAR algorithm                                  %
%-------------------------------------------------------------------------%

for j=1:points
    input=x(j);
    n_out=SuccAppr(input,nbit, yDAC);
out(j)=n_out;
end

%------------------------------Graphics-----------------------------------%
%                                                                         %
%   figure(1)  -->  Figure 4.31 page 181                                  %
%   figure(2)  -->  Figure 4.32 page 182                                  %
%                                                                         %
%-------------------------------------------------------------------------%

n_bin=2^nbit-1;
[DNL,INL,ideal,real,in,co,edges] = INL_DNL_R(x,out,n_bin);
figure (1);
plot(DNL);
xlim([0 n_bin]);
title('DNL with an average of 50 samples per bin');
grid;
figure (2)
plot(INL)
xlim([0 n_bin]);
title('INL with distortion terms');
grid;


    
    
