%**************************************************************************
% Direct Sequence Spread Spectrum Transmitter/Receiver systems simulation
%            
%**************************************************************************

clc
close all
clear all

R = 100;                 % The length of the bit stream.
S = 63;                    % Bit duration(each bit is represented with 
                                % S samples of the waveform used in signaling.
snr = 1;	      %Signal to noise ratio
bit_stream = round(rand(1,R));  % A Randomly Generated Bit Stream.    
PAM = zeros(1,S*R);             % Predefinition of the Base-band PAM signal.

% Generating the PAM signal using Polar Non-Return-to-Zero signaling. Every
% S samples corresponds to one bit.
for i = 1:R
    if bit_stream(1,i)== 0
        PAM(1+(i-1)*S : i*S) = -1;
    else
        PAM(1+(i-1)*S : i*S) =  1;
    end
end

subplot(3,2,1)
plot(PAM);
axis([-1 S*R+10 -1.5 1.5]);
title('Base-Band PAM Signal');
subplot(3,2,2);
 pwelch(PAM,[],[],[],S,[],'db');
  axis([0 S/2 -80 0]);

title('PSD of the PAM signal');

% Generating the pseudo random SEQUENCE for spreading.
pn_seq = round(rand(1,S));

% Generating the pseudo random SIGNAL for spreading.

pn_sig_tx = zeros(1,(S*R));   % Pseudo Noise signal in the tx.
for i = 1:S
    if pn_seq(1,i)==0
        for j = 1:R
        pn_sig_tx(1,i+S*(j-1)) = -1;
        end
    else
        for j = 1:R
        pn_sig_tx(1,i+S*(j-1)) =  1;
        end 
    end  
    %carrier=[carrier c];
end

%partial plot of the PN sequency
subplot(3,2,3);
plot(pn_sig_tx)
axis([1 126 -1.5 1.5]);
title('partial plot of the PN sequency');
subplot(3,2,4);
pwelch(pn_sig_tx,[],[],[],R*S,[],'db');
 axis([0 S*R/2 -80 0]);

%DSSS Modulation
spreaded_sig = PAM.* pn_sig_tx;


%partial plot of the DSSS signal
subplot(3,2,5);
plot(spreaded_sig)
axis([1 126 -1.5 1.5]);
title('Spreaded signal');
% PSD of the spreaded signal.
subplot(3,2,6);
pwelch(spreaded_sig,[],[],[],R*S,[],'db');
 axis([0 S*R/2 -80 0]);
title('PSD of the spreaded signal');

% channel AWGN (Added Gaussian Noise)

spreaded_sig_n=awgn(spreaded_sig,snr);
figure(2);
subplot(2,1,1);
plot(spreaded_sig_n)
title('Spreaded signal+Noise');
subplot(2,1,2);
pwelch(spreaded_sig_n,[],[],[],R*S,[],'db');
 axis([0 S*R/2 -80 0]);
