Code covered by the BSD License  

Highlights from
Wave modulation illustrator

image thumbnail
from Wave modulation illustrator by Alain Demange
This GUI/Tool may help you to understand properties for various types of waves modulations.

Analog_Modulation(varargin)
function varargout = Analog_Modulation(varargin)
% ANALOG_MODULATION M-file for Analog_Modulation.fig
%      ANALOG_MODULATION, by itself, creates a new ANALOG_MODULATION or raises the existing
%      singleton*.
%
%      H = ANALOG_MODULATION returns the handle to a new ANALOG_MODULATION or the handle to
%      the existing singleton*.
%
%      ANALOG_MODULATION('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in ANALOG_MODULATION.M with the given input
%      arguments.
%
%      ANALOG_MODULATION('Property','Value',...) creates a new ANALOG_MODULATION or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before Analog_Modulation_OpeningFunction gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to Analog_Modulation_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Copyright 2002-2003 The MathWorks, Inc.

% Edit the above text to modify the response to help Analog_Modulation

% Last Modified by GUIDE v2.5 20-May-2009 07:51:14

% Author: Alain DEMANGE, alain.demange0382@orange.fr

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @Analog_Modulation_OpeningFcn, ...
                   'gui_OutputFcn',  @Analog_Modulation_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before Analog_Modulation is made visible.
function Analog_Modulation_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to Analog_Modulation (see VARARGIN)

% Choose default command line output for Analog_Modulation
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes Analog_Modulation wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = Analog_Modulation_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

%-----------------------------------------------------------------------------------%

%-------------------------------INITIAL SETTINGS------------------------------------%
set(handles.modChoice,'Value',1)    % Modulation set to DSB-SC 
set(handles.modParam,'Visible','Off');
set(handles.text21,'Visible','Off');
set(handles.demodMethod,'Value',1)  % Demodulation set to Coherent
set(handles.text14,'Visible','On');
set(handles.DemodSetting_1,'Visible','On');
set(handles.text13,'Visible','On');
set(handles.DemodSetting_2,'Visible','On');
set(handles.PLLOutputFilter,'Visible','Off');
set(handles.noiseConfToggle,'Value',1); %  SNR noise mode entry setting
set(handles.noiseConfToggle,'String','Signal to noise ratio selected');
set(handles.ampLimit,'Value',0);                % Magnitude clipping not enable
set(handles.soundCommand,'Visible','Off');      % Not yet file to sound!
set(handles.plotCommand,'Visible','Off');       % Not yet results to plot!
set(handles.mainButton,'Visible','Off');        % Not yet .wav file selected!
set(handles.ValidityResults,'Visible','Off');
set(handles.LFgenSelection,'Value',1);          % Sine LF generator selected
sineLFGenParamVisibility(handles)               % Display sine LF generator settings windows
set(handles.demodOut,'Visible','Off');

% Run transmission process indicator
Busy = 0; 
handles.Busy = Busy;

% Initialize "modifications flag" in order to indicate if some configuration
% parameters have been modified after the last transmission simulation.
firstSettingsFlag =1;
handles.firstSettingsFlag = firstSettingsFlag;
guidata(hObject,handles);

% Load file listbox from initial directory
initial_dir = pwd;  
load_listbox(initial_dir,handles)

%---------------------------------MAIN FUNCTION6------------------------------------%

% --- Executes on button press in mainButton.
function mainButton_Callback(hObject, eventdata, handles)

% Prepare the window which displays required results after simulations. 
figure(1)
set(gcf,'Name','Results')
set(gcf,'Visible','Off');
set(handles.soundCommand,'Visible','Off');      
set(handles.plotCommand,'Visible','Off');
set(handles.ValidityResults,'Visible','Off');

% verify if simulation is not already running and modify mainButton color if
% necessary
Busy = handles.Busy;
if Busy == 1
    return
end
Busy = 1;
firstSettingsFlag = 0;
handles.firstSettingsFlag = firstSettingsFlag;
set(handles.mainButton,'Backgroundcolor',[1 0 0]);
set(handles.mainButton,'String','Busy!');
 
pause(0.1)


% Read configuration values
Fs_min = str2double(get(handles.minFreq,'String')); %Initial variables settings
Fs_max = str2double(get(handles.maxFreq,'String'));
Fp = str2double(get(handles.carrierFreq,'String'));
A0 = str2double(get(handles.A0,'String'));
Clip_Lvl = str2double(get(handles.clipLvl,'String'));
Gain = str2double(get(handles.Gain,'String'));
Phi_error = eval(get(handles.DemodSetting_1,'String'));
F_error = eval(get(handles.DemodSetting_2,'String'));
k_fad = str2double(get(handles.k_fad,'String'));
NF = str2double(get(handles.NF,'String'));
SNR = str2double(get(handles.SNR,'String'));

% Select sources data
if get(handles.toggleSource,'Value') == 0
    Fes = handles.Fes;              % Audio source data
    S_primaire = handles.S_primaire;%
    k = ceil(str2double(get(handles.CarrierSampFactIn,'String')) ...
        *(Fp + str2double(get(handles.SourceSampFactorIn,'String'))*Fs_max)/Fes); % Upsample factor                               
    Fesim = k*Fes;                  % Simulation sample frequency
    handles.Fesim = Fesim;
    Sequence = repmat(S_primaire',k,1);
    Sequence = Sequence (:);
    clear k;
else                           
    switch(get(handles.LFgenSelection,'Value'))
        case 1  % Single Tone generator
            Fesim = str2double(get(handles.CarrierSampFactIn,'String')) ...
                *(Fp + str2double(get(handles.LFgenFrequency,'String'))); % Simulation sample frequency
            samplePerPeriod = ceil(Fesim/str2double(get(handles.LFgenFrequency,'String')));
            outLFGen = 0.5*str2double(get(handles.LFgenLevel,'String')) ...
                *cos(2*pi*str2double(get(handles.LFgenFrequency,'String'))*[0:samplePerPeriod-1]/Fesim)...
                + str2double(get(handles.LFgenOffset,'String'));
            outLFGen = repmat(outLFGen',str2double(get(handles.LFgenPeriods,'String')),1);

        case 2  % Rectangular/ sawtooth generator
            Fesim = str2double(get(handles.CarrierSampFactIn,'String')) ...
                *(Fp + str2double(get(handles.SourceSampFactorIn,'String')) ...
                *str2double(get(handles.LFgenFrequency,'String'))); % Simulation sample frequency
            minAmp = str2double(get(handles.LFgenOffset,'String')) - str2double(get(handles.LFgenLevel,'String'))/2;
            maxAmp = str2double(get(handles.LFgenOffset,'String')) + str2double(get(handles.LFgenLevel,'String'))/2;
            riseTime = eval(get(handles.LFgenParam_4,'String'));
            fallTime = eval(get(handles.LFgenParam_5,'String'));
            widthHigh = eval(get(handles.LFgenParam_6,'String'));
            period = 1/(str2double(get(handles.LFgenFrequency,'String')));
            periodNumber = str2double(get(handles.LFgenPeriods,'String'));
            
            if (riseTime+fallTime+widthHigh) > period
                errordlg('Erreur: Risetime+Falltime+Width > 1/frequency', ...
                    'Input value error')
                return
            end

            if riseTime == 0
                risePart = maxAmp;
            else
                delta = (maxAmp - minAmp)/round(riseTime*Fesim);
                risePart = [minAmp:delta:maxAmp];
            end

            highPart = maxAmp*ones(1,round(widthHigh*Fesim));

            if fallTime == 0
                fallPart = minAmp;
            else
                delta = (maxAmp - minAmp)/round(fallTime*Fesim);
                fallPart = [maxAmp:-delta:minAmp];
            end
            lowPart = minAmp*ones(1,(round(period*Fesim)- length(risePart) - length(highPart) - length(fallPart)));
            baseSignal = [risePart highPart fallPart lowPart];
            outLFGen  = repmat(baseSignal',periodNumber,1);
            clear baseSignal risePart highPart fallPart lowPart period delta maxAmp;
            clear minAmp widthHigh period periodNumber riseTime fallTime;
            
        case 3 % m-ary NRZ random sequence
            Fesim = str2double(get(handles.CarrierSampFactIn,'String')) ...
                *(Fp + str2double(get(handles.LFgenFrequency,'String'))); % Simulation sample frequency
            samplePerPeriod = ceil(Fesim/str2double(get(handles.LFgenFrequency,'String')));
            periodNumber = str2double(get(handles.LFgenPeriods,'String'));
            stateNumber = str2double(get(handles.LFgenParam_4,'String'));
            if sum(factor(stateNumber)~=2)~=0;
                errordlg('The number of state/symbole is not a power of two','Value error')
            end
            %outLFGen = 2*randint(1,periodNumber,stateNumber)-stateNumber+1;
            outLFGen = 2*floor(stateNumber*rand(1,periodNumber))-stateNumber+1;
            outLFGen = repmat(outLFGen,samplePerPeriod,1);
            outLFGen = outLFGen(:);
            magFactor = str2double(get(handles.LFgenLevel,'String'))/(2*(stateNumber-1));
            outLFGen = outLFGen*magFactor + str2double(get(handles.LFgenOffset,'String'));
            clear magFactor stateNumber samplePerPeriod periodNumber;
        case 4 % Uniformly distributed number in range "level"
            Fesim = str2double(get(handles.CarrierSampFactIn,'String'))*Fp;
            outLFGen = rand(str2double(get(handles.LFgenOffset,'String')),1)-0.5;
            outLFGen = str2double(get(handles.LFgenLevel,'String'))*outLFGen;
            
    end 
    handles.Fesim = Fesim;
    Sequence =outLFGen;
    clear outLFGen;
end


t=[1:numel(Sequence)]/Fesim;     % Time vector
handles.time = t;


Original_sequence = Sequence;    % Primary source copy in order to eventualy display it.
handles.Original_sequence = Original_sequence;


% Source frequency band reduction if required
if get(handles.SourceFreqControlValidation, 'Value') == 1
    if get(handles.MatlabModulestoggle,'Value') == 0
        if str2double(get(handles.minFreq,'String')) == 0
            num =0.5*firFilter(-Fs_max,Fs_max,30,Fesim,'Blackman',handles);
        else
            num =firFilter(Fs_min,Fs_max,30,Fesim,'Blackman',handles);
        end
        den = 1;
    else
        if str2double(get(handles.minFreq,'String')) ~= 0
            [num,den] = cheby1(6,1,2*Fs_min/Fesim,'high');  % High pass filter
            Sequence = filter (num,den,Sequence);
        else
            [num,den] = ellip(7,1,60,2*Fs_max/Fesim);       % Low pass filter coefficients
        end
    end
    Filtered_Sequence = filter (num,den,Sequence);
    clear num den Sequence;
else
    Filtered_Sequence = Sequence;
end
clear Sequence;
handles.Filtered_Sequence = Filtered_Sequence;


% Carrier modulation
switch(get(handles.modChoice,'Value'))
    case 1 % DSB-SC
        envelope = Filtered_Sequence*A0;
        Out_EX = envelope .* cos(2*pi*Fp.*t') ; 
    case 2 % DSB-TC
        ka = str2double(get(handles.modParam,'String'));
        envelope = (1+ka*Filtered_Sequence)*A0;
        Out_EX = envelope .* cos(2*pi*Fp.*t') ;
    case 3 % SSB-USB (Weaver method)
        F1 = (Fs_min +Fs_max)/2; % Center frequency of baseband signal for second mixer        
        [envelope Out_EX] = VeawerSSB(1,Filtered_Sequence,(Fs_min +Fs_max)/2,Fp,A0,Fesim,t,handles);     
    case 4 % SSB-LSB (Weaver method)
        F1 = (Fs_min +Fs_max)/2; % Center frequency of baseband signal for second mixer        
        [envelope Out_EX] = VeawerSSB(-1,Filtered_Sequence,(Fs_min +Fs_max)/2,Fp,A0,Fesim,t,handles);
    case 5 % VSB-USB
        envelope = Filtered_Sequence*A0; % Improper designation here but easy for future plot 
        [Out_EX] = RF_VSB(1,7,Filtered_Sequence,Fp,A0,Fesim,t,handles);   
    case 6 % VSB-LSB
         envelope = Filtered_Sequence*A0; % Improper designation here but easy for future plot 
        [Out_EX] = RF_VSB(-1,7,Filtered_Sequence,Fp,A0,Fesim,t,handles);        
    case 7 % FM using VCO structure
        envelope = Filtered_Sequence*A0; % Improper designation here but easy for future plot 
        Alpha =str2double(get(handles.modParam,'String')); % VCO frequency slope 
        SumSequence = mod((2*pi*cumsum(Fp + Alpha*Filtered_Sequence)/Fesim),2*pi); %gnration de la phase  partir du signal informatif mod 2 pi
        Out_EX = A0*cos(SumSequence);
    case 8  % Phase modulation (IQ modulator)
        envelope = Filtered_Sequence*A0; % Improper designation here but easy for future plot 
        Alpha = eval(get(handles.modParam,'String')); % Phase index modulation
        Env_I = cos(mod(Alpha * Filtered_Sequence,2*pi)) .* (A0*cos(2*pi*Fp.*t')); % Complex envelope chanel I
        Env_Q = sin(mod(Alpha * Filtered_Sequence,2*pi)) .* (A0*sin(2*pi*Fp.*t')); % Complex envelope chanel Q
        Out_EX = Env_I - Env_Q;
end

handles.envelope = envelope;

% Transmitter output level control
Out_EX = str2double(get(handles.Gain,'String'))*Out_EX; % Modulated carrier amplification
if get(handles.ampLimit,'Value') == 1
Clip_Lvl = str2double(get(handles.clipLvl,'String'));
Out_EX = max(min(Out_EX,Clip_Lvl),-Clip_Lvl);   % Output limited to +- Clip_Lvl 
end
handles.Out_EX = Out_EX;

% CHANNEL LIMITATIONS
% Fading
Ffading = str2double(get(handles.freqFading,'String'));
if Ffading ~= 0
    k_fad = str2double(get(handles.k_fad,'String'));
    In_RX =   (1+ k_fad*sin(2*pi*Ffading.*t')).* Out_EX;
else
    In_RX = Out_EX;
end

% Adding noise
if get(handles.noiseConfToggle,'Value') == 1
    SNR = str2double(get(handles.SNR,'String'));
    NF = std(In_RX)/(10^(SNR/20));
else
    NF = str2double(get(handles.NF,'String'));
end
if NF ~= 0
    In_RX= In_RX + NF*randn(size(In_RX));
end

% Front end receiver channel filtering
if get(handles.Rx_filter,'Value') == 1
    Rx_Band = eval(get(handles.Rx_Band_In,'String'));
    
    if get(handles.MatlabModulestoggle,'Value') == 0
        num =firFilter(Fp-Rx_Band/2,Fp+Rx_Band/2,30,Fesim,'Blackman',handles);
        den = 1;
    else
        [num,den] = ellip(7,1,60,2*(Fp-Rx_Band/2)/Fesim,'high'); % High pas filter
        In_RX = filter (num,den,In_RX);
        [num,den] = ellip(7,1,60,2*(Fp+Rx_Band/2)/Fesim); % Low pass filter coefficients
    end    
    In_RX = filter (num,den,In_RX);
end
handles.In_RX = In_RX;

% Demodulation
if get(handles.EnableDemodButton,'Value')== 1
    switch(get(handles.demodMethod,'Value'))
        case 1 % Coherent (I) demodulation
            Demod_out = In_RX .* (2*A0*cos(2*pi*(Fp+F_error).*t'+Phi_error));
            if get(handles.MatlabModulestoggle,'Value') == 0
                num =0.5*firFilter(-Fs_max,Fs_max,30,Fesim,'Blackman',handles);
                den = 1;
            else
                [num den] = butter(5,2*Fs_max/Fesim);
            end
            RX_Sequence = filter (num,den,Demod_out);

        case 2 % Envelope (Phase recovering from complex envelope)
            In_Demod_T_I = In_RX .* (A0*cos(2*pi*Fp.*t'+ Phi_error));
            In_Demod_T_Q = In_RX .* (A0*sin(2*pi*Fp.*t'+ Phi_error));
            if get(handles.MatlabModulestoggle,'Value') == 0
                num =0.5*firFilter(-Fs_max,Fs_max,30,Fesim,'Blackman',handles);
                den = 1;
            else
                [num,den] = butter(3,2*Fs_max/Fesim);
            end
            RX_Sequence_I = filter (num,den,In_Demod_T_I);
            RX_Sequence_Q = filter (num,den,In_Demod_T_Q);
            Tg_RX_Sequence =-RX_Sequence_Q ./ RX_Sequence_I; % tg(Phi(t)) estimation
            RX_Sequence= 0.5*unwrap(2*atan(Tg_RX_Sequence)); % Phase estimation

            if get(handles.modChoice,'Value') == 7           % Case of FM modulation choosed
                RX_Sequence = [diff(RX_Sequence);0]*Fesim/(2*pi*Alpha);   % Phase derivative plus amplitude normalization
            else
             % correction in order to limit phase accumulation
            RX_Sequence = RX_Sequence-mean(RX_Sequence);
            RX_Sequence = max(min(RX_Sequence,1.5*std(RX_Sequence)),-1.5*std(RX_Sequence));    
            end

        case 3 % Envelope (Magnitude of complex envelope recovering)
            if get(handles.MatlabModulestoggle,'Value') == 0
                num =0.5*firFilter(-Fs_max,Fs_max,30,Fesim,'Blackman',handles);
                den = 1;
            else
                [num den] = butter(5,2*Fs_max/Fesim);
            end
            Demod_out_I = In_RX .* (A0*cos(2*pi*Fp.*t'+Phi_error));
            Demod_out_I = filter (num,den,Demod_out_I);     % I Channel
            Demod_out_Q = In_RX .* (A0*sin(2*pi*Fp.*t'+Phi_error));
            Demod_out_Q = filter (num,den,Demod_out_Q);     % Q channel
            RX_Sequence = sqrt(Demod_out_I.^2 + Demod_out_Q.^2);
            RX_Sequence = RX_Sequence - mean(RX_Sequence);
            clear Demod_out_Q Demod_out_I;

        case 4 % Rectified carrier average
            RX_Sequence = In_RX.*(In_RX >0); % Half-wave rectification.
            if get(handles.MatlabModulestoggle,'Value') == 0 
                num =0.5*firFilter(-Fs_max,Fs_max,30,Fesim,'Blackman',handles);
                den = 1;
            else
                [num den] = butter(5,2*Fs_max/Fesim);
            end

            RX_Sequence = filter (num,den,RX_Sequence);
            RX_Sequence = RX_Sequence-mean(RX_Sequence);


        case 5 % Pulse average method for FM modulation
            DeltaF = str2double(get(handles.modParam,'String'))... 
                *max(abs(Filtered_Sequence));
            [RX_Sequence] = pulseAverage(In_RX,1.5,DeltaF,Fs_max,Fp,Fesim,handles);
            RX_Sequence = std(Filtered_Sequence)/std(RX_Sequence)*RX_Sequence; % Level adjustment


        case 6 % PLL demodulation
             [RX_Sequence] = PLLdemod (In_RX,A0,Fs_max,Fesim,handles);       
    end
    handles.RX_Sequence = RX_Sequence;
    set(handles.demodOut,'Visible','On');
else
    set(handles.demodOut,'Visible','Off');
end
set(handles.ValidityResults,'String','Results and Transmission settings are in accordance');
set(handles.ValidityResults,'Backgroundcolor',[0 1 0]);
set(handles.ValidityResults,'Visible','On');

Busy = 0; 
handles.Busy = Busy;
set(handles.mainButton,'String','GO ! !')
set(handles.mainButton,'Backgroundcolor',[0 1 0]);
guidata(hObject,handles);
set(handles.plotCommand,'Visible','On');
set(handles.soundCommand,'Visible','On');

%-----------------------------------------------------------------------------------%
function Chemin_Callback(hObject, eventdata, handles)
cd (get(handles.Chemin,'String'));
load_listbox(pwd,handles);

% --- Executes during object creation, after setting all properties.
function Chemin_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
% --- Executes on selection change in mylistbox.
function mylistbox_Callback(hObject, eventdata, handles)

settingsModification(handles);

if strcmp(get(handles.figure1,'SelectionType'),'open')
	index_selected = get(handles.mylistbox,'Value');
	file_list = get(handles.mylistbox,'String');	
	filename = file_list{index_selected};
	if  handles.is_dir(handles.sorted_index(index_selected))
		cd (filename)
		load_listbox(pwd,handles)
	else
	   [path,name,ext,ver] = fileparts(filename);
       sourceFile = [pwd '\' name ext];
       set(handles.Chemin,'String',sourceFile);
       [S_primaire, Fes] = wavread(sourceFile);
       handles.S_primaire = S_primaire;
       handles.Fes = Fes;
       guidata(hObject,handles);
       set(handles.mainButton,'Visible','On');
   end
end


% --- Executes during object creation, after setting all properties.
function mylistbox_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
% Read the current directory and sort the names (directory and .vaw only)
function load_listbox(dir_path,handles)
cd (dir_path)
dir_struct = dir(dir_path);
a = {dir_struct.name}';
b = [dir_struct.isdir]; 
validFilesNames={};
dirNames = {};
for i = 1:length(a)
    if length(a{i})>= 3 % Search for .vaw extension
        flipExt =fliplr(a{i});    
        if (flipExt(1:3) == 'vaw')  | (flipExt(1:3) == 'VAW')
            validFilesNames = [validFilesNames ; a(i)];
            
        end
    end
    if b(1,i) % search for directories
        dirNames = [dirNames ; a(i)];
        
    end
end

[sorted_Dir] = sort(dirNames);
[sorted_FileNames] = sort(validFilesNames);
sorted_names = [sorted_Dir ; sorted_FileNames];
sorted_index = 1:(length(sorted_Dir) +length(sorted_FileNames));
dirFlagsList = [ones(1,length(sorted_Dir)) zeros(1,length(sorted_FileNames))];
handles.file_names = sorted_names;
handles.is_dir = dirFlagsList;
handles.sorted_index = sorted_index;
guidata(handles.figure1,handles);
set(handles.mylistbox,'String',handles.file_names,'Value',1);
set(handles.Chemin,'String',pwd);

%-----------------------------------------------------------------------------------%
% --- Executes during object creation, after setting all properties.
function figure1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called
setappdata(hObject, 'StartPath', pwd);
addpath(pwd);

% --- Executes during object deletion, before destroying properties.
function figure1_DeleteFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
if isappdata(hObject, 'StartPath')
    rmpath(getappdata(hObject, 'StartPath'));
end



%-----------------------------------------------------------------------------------%
% --- Executes on selection change in modChoice.
function modChoice_Callback(hObject, eventdata, handles)

switch get(handles.modChoice,'Value')
    case 2
        set(handles.modParam,'Visible','On');
        set(handles.modParam,'String','1');
        set(handles.text21,'String','DSB-TC mod.index:');
        set(handles.text21,'Visible','On');
    case 5
        set(handles.modParam,'Visible','On');
        set(handles.modParam,'String','25');
        set(handles.text21,'String','VSB (% of baseband width)');
        set(handles.text21,'Visible','On');
    case 6
        set(handles.modParam,'Visible','On');
        set(handles.modParam,'String','25');
        set(handles.text21,'String','VSB (% of baseband width)');
        set(handles.text21,'Visible','On');
    case 7
        set(handles.modParam,'Visible','On')
        set(handles.modParam,'String','1000');
        set(handles.text21,'String','Frequency slope (Hz/u):')
        set(handles.text21,'Visible','On');
    case 8
        set(handles.modParam,'Visible','On')
        set(handles.modParam,'String','1');
        set(handles.text21,'String','PM mod.index (rd/u):')
        set(handles.text21,'Visible','On');
    otherwise
        set(handles.modParam,'Visible','Off');
        set(handles.text21,'Visible','Off');
end

settingsModification(handles);
        
% --- Executes during object creation, after setting all properties.
function modChoice_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



%-----------------------------------------------------------------------------------%
% --- Executes on selection change in demodMethod.
function demodMethod_Callback(hObject, eventdata, handles)

settingsModification(handles);
 
switch get(handles.demodMethod,'Value')
    case 1 
        set(handles.text14,'String','Rx LO phase  error (rd)','Visible','On');
        set(handles.DemodSetting_1,'String','0','Visible','On');
        set(handles.text13,'String','Rx LO frequency error (Hz)','Visible','On');
        set(handles.DemodSetting_2,'String','0','Visible','On');
        set(handles.PLLOutputFilter,'Visible','Off');
    case 2
        set(handles.text14,'String','Rx LO phase  error (rd)','Visible','On');
        set(handles.DemodSetting_1,'String','0','Visible','On');
        set(handles.text13,'String','Rx LO frequency error (Hz)','Visible','On');
        set(handles.DemodSetting_2,'String','0','Visible','On');
        set(handles.PLLOutputFilter,'Visible','Off');
    case 3
        set(handles.text14,'String','Rx LO phase  error (rd)','Visible','On');
        set(handles.DemodSetting_1,'String','0','Visible','On');
        set(handles.text13,'String','Rx LO frequency error (Hz)','Visible','On');
        set(handles.DemodSetting_2,'String','0','Visible','On');
        set(handles.PLLOutputFilter,'Visible','Off');
    case 6
        set(handles.text14,'String','Damping factor','Visible','On');
        set(handles.DemodSetting_1,'String','1','Visible','On');
        set(handles.text13,'String','Loop nat. frequency','Visible','On');
        a = get(handles.maxFreq,'String');
        set(handles.DemodSetting_2,'String',a,'Visible','On');
        set(handles.PLLOutputFilter,'Visible','On');
        
    otherwise
        set(handles.text14,'Visible','Off');
        set(handles.DemodSetting_1,'Visible','Off');
        set(handles.text13,'Visible','Off');
        set(handles.DemodSetting_2,'Visible','Off');
        set(handles.PLLOutputFilter,'Visible','Off');
end


% --- Executes during object creation, after setting all properties.
function demodMethod_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function minFreq_Callback(hObject, eventdata, handles)
settingsModification(handles);


% --- Executes during object creation, after setting all properties.
function minFreq_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function maxFreq_Callback(hObject, eventdata, handles)
settingsModification(handles);


% --- Executes during object creation, after setting all properties.
function maxFreq_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function carrierFreq_Callback(hObject, eventdata, handles)
settingsModification(handles);


% --- Executes during object creation, after setting all properties.
function carrierFreq_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function A0_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function A0_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function clipLvl_Callback(hObject, eventdata, handles)
settingsModification(handles);


% --- Executes during object creation, after setting all properties.
function clipLvl_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function Gain_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function Gain_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
% --- Executes on button press in ampLimit.
function ampLimit_Callback(hObject, eventdata, handles)
settingsModification(handles);

%-----------------------------------------------------------------------------------%
function edit10_Callback(hObject, eventdata, handles)

% --- Executes during object creation, after setting all properties.
function edit10_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function edit11_Callback(hObject, eventdata, handles)


% --- Executes during object creation, after setting all properties.
function edit11_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function DemodSetting_1_Callback(hObject, eventdata, handles)
settingsModification(handles);



% --- Executes during object creation, after setting all properties.
function DemodSetting_1_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
function freqFading_Callback(hObject, eventdata, handles)
settingsModification(handles);


% --- Executes during object creation, after setting all properties.
function freqFading_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function k_fad_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function k_fad_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function NF_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function NF_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function SNR_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function SNR_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
% --- Executes on button press in noiseConfToggle.
function noiseConfToggle_Callback(hObject, eventdata, handles)
settingsModification(handles);
SNR_NF = get(handles.noiseConfToggle,'Value');
if SNR_NF == 0
    set(handles.noiseConfToggle,'String','Noise amp. factor selected')
else
    set(handles.noiseConfToggle,'String','Signal to noise ratio selected')
end

%-----------------------------------------------------------------------------------%
% --- Executes on selection change in soundMenu.
function soundMenu_Callback(hObject, eventdata, handles)


% --- Executes during object creation, after setting all properties.
function soundMenu_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
% --- Executes on button press in soundCommand.
function soundCommand_Callback(hObject, eventdata, handles)
Fesim = handles.Fesim;
switch get(handles.soundMenu,'Value')
    case 1
        Original_sequence = handles.Original_sequence;
        sound(Original_sequence,Fesim);
    case 2
       Filtered_Sequence = handles.Filtered_Sequence;
        sound(Filtered_Sequence,Fesim);
    case 3
       Out_EX = handles.Out_EX;
        sound(Out_EX,Fesim);
    case 4
        RX_Sequence = handles.RX_Sequence;
        sound(RX_Sequence,Fesim);
end

%-----------------------------------------------------------------------------------%
% --- Executes on button press in basebandSourceDsplay.
function basebandSourceDsplay_Callback(hObject, eventdata, handles)

%-----------------------------------------------------------------------------------%
% --- Executes on button press in basebandSourceDsplay_1.
function basebandSourceDsplay_1_Callback(hObject, eventdata, handles)

%-----------------------------------------------------------------------------------%
% --- Executes on button press in tempSlicedBsbdCarrier.
function tempSlicedBsbdCarrier_Callback(hObject, eventdata, handles)

%-----------------------------------------------------------------------------------%
% --- Executes on button press in frontEndPsd.
function frontEndPsd_Callback(hObject, eventdata, handles)

%-----------------------------------------------------------------------------------%
% --- Executes on button press in frontEndReceiverTemporal.
function frontEndReceiverTemporal_Callback(hObject, eventdata, handles)


%-----------------------------------------------------------------------------------%
% --- Executes on button press in demodOut.
function demodOut_Callback(hObject, eventdata, handles)

%-----------------------------------------------------------------------------------%
function modParam_Callback(hObject, eventdata, handles)
settingsModification(handles); 


% --- Executes during object creation, after setting all properties.
function modParam_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
% --- Executes during object creation, after setting all properties.
function text21_CreateFcn(hObject, eventdata, handles)

%-----------------------------------------------------------------------------------%
function freqError_Callback(hObject, eventdata, handles)
settingsModification(handles);


%-----------------------------------------------------------------------------------%
% --- Executes on button press in plotCommand.
function plotCommand_Callback(hObject, eventdata, handles)

Nfft = eval (get(handles.NFFT_in,'String'));
if sum(factor(Nfft)~=2)~=0;
    errordlg('The FFT length is not a power of two. Please, correct it !','Value error')
    return
end

numplot = 0;            % Used in subplot(NumRawSubplot,1,numplot)
NumRawSubplot = 0;      % 

% find the number of axes in subplot
if get(handles.basebandSourceDsplay,'Value') == 1
    NumRawSubplot = NumRawSubplot + 1;
end
if (get(handles.basebandSourceDsplay_1,'Value')) == 1 
    NumRawSubplot = NumRawSubplot + 1;
end
if get(handles.tempSlicedBsbdCarrier,'Value') == 1
    NumRawSubplot = NumRawSubplot + 1;
end
if get(handles.frontEndPsd,'Value') == 1
    NumRawSubplot = NumRawSubplot + 1;
end
if get(handles.frontEndReceiverTemporal,'Value') == 1
    NumRawSubplot = NumRawSubplot + 1;
end
if (get(handles.demodOut,'Value') == 1) && (get(handles.EnableDemodButton,'Value')== 1)
    NumRawSubplot = NumRawSubplot + 1;
end

if NumRawSubplot ~= 0
    figure(1)
    set(gcf,'Visible','On')
else
    figure(1)
    set(gcf,'Visible','Off')
    return
end
    
    
Fesim = handles.Fesim;
    
% Display the required axes
if get(handles.basebandSourceDsplay,'Value') == 1
    numplot = numplot+1;
    subplot(NumRawSubplot,1,numplot)

    if get(handles.SourceFreqControlValidation, 'Value') == 1
        Original_sequence = handles.Original_sequence;
        Filtered_Sequence = handles.Filtered_Sequence;
        [errFlag Psd0 freq] = myPSD(Original_sequence,Nfft,Fesim,handles);
        [errFlag Psd1 freq] = myPSD(Filtered_Sequence,Nfft,Fesim,handles) ;
        if errFlag == 0
            plot (freq,10*log10(Psd0),'b' , freq, 10*log10(Psd1),'r')
            title ('Source power spectrum before (blue) et after filter (red)')
        end
    else
        Original_sequence = handles.Original_sequence;
        [errFlag Psd0 freq] = myPSD(Original_sequence,Nfft,Fesim,handles);
        if errFlag == 0
            plot (freq,10*log10(Psd0))
            title ('Source power spectrum')
        end      
    end
        xlabel('Frequency (Hz)')
        ylabel('dB')
        grid
end

if get(handles.basebandSourceDsplay_1,'Value') == 1
    t=handles.time;
    %RX_Sequence = handles.RX_Sequence;
    Filtered_Sequence = handles.Filtered_Sequence;
    numplot = numplot+1;
    subplot(NumRawSubplot,1,numplot)
    if get(handles.toggleSource, 'Value') == 1
        plot(t, Filtered_Sequence, 'b')
    else
        plot(t(1,10000:35000), Filtered_Sequence(10000:35000,1))
    end
    xlabel('time (s)')
    title('Modulating source')
    grid
end

if get(handles.tempSlicedBsbdCarrier,'Value') == 1
    t=handles.time;
    Out_EX = handles.Out_EX;
    envelope = handles.envelope;
    numplot = numplot+1;
    subplot(NumRawSubplot,1,numplot)
    if get(handles.toggleSource,'Value') == 0
        plot(t(1,3000:8000),[Out_EX(3000:8000,1) envelope(3000:8000,1)])
    else
        plot(t,Out_EX,'r',t,envelope,'b')
    end
    xlabel('time (s)')
    title ('Output of emitter (red)  surperposed on source (blue)')
    grid

end

if get(handles.frontEndPsd,'Value') == 1
    In_RX = handles.In_RX;
    numplot = numplot + 1;
    subplot (NumRawSubplot,1,numplot)
    [errFlag Psd freq] = myPSD(In_RX,Nfft,Fesim,handles);
    if errFlag == 0
    plot (freq, 10*log10(Psd))
    grid
    xlabel('Frequency (Hz)')
    ylabel('dB')
    title('Input demodulator power spectrum')
    end
end

if get(handles.frontEndReceiverTemporal,'Value') == 1
    t=handles.time;
    In_RX = handles.In_RX;
    numplot = numplot + 1;
    subplot (NumRawSubplot,1,numplot)

    if get(handles.toggleSource, 'Value') == 0
        plot(t(1,3000:8000),In_RX(3000:8000,1))
    else
        plot(t,In_RX)
    end
    xlabel('time (s)')
    title('Receiver (temporal) input')
    grid

end

if get(handles.demodOut,'Value') == 1 && (get(handles.EnableDemodButton,'Value')== 1)
    t=handles.time;
    RX_Sequence = handles.RX_Sequence;
    Filtered_Sequence = handles.Filtered_Sequence;
    numplot = numplot + 1;
    subplot (NumRawSubplot,1,numplot)
    if get(handles.toggleSource, 'Value') == 1
        plot(t,RX_Sequence,'r', t, Filtered_Sequence, 'b')
    else
        plot(t(1,10000:35000),RX_Sequence(10000:35000,1),'b',t(1,10000:35000), Filtered_Sequence(10000:35000,1),'r')
    end
    xlabel('time (s)')
    title('Partial output of demodulator (blue) compared to source (red)')
    grid
end

%-----------------------------------------------------------------------------------%
function NFFT_in_Callback(hObject, eventdata, handles)


% --- Executes during object creation, after setting all properties.
function NFFT_in_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function Rx_Band_In_Callback(hObject, eventdata, handles)
settingsModification(handles);
% --- Executes during object creation, after setting all properties.
function Rx_Band_In_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
% --- Executes on button press in Rx_filter.
function Rx_filter_Callback(hObject, eventdata, handles)
settingsModification(handles);
if get(handles.Rx_filter,'Value') == 0
    set(handles.Rx_filter,'String','Filter Off');
else
    set(handles.Rx_filter,'String','Filter On');
end

%-----------------------------------------------------------------------------------%
function settingsModification(handles)

firstSettingsFlag = handles.firstSettingsFlag;
if firstSettingsFlag == 1
    return % First settings
else
    set(handles.ValidityResults,'String','WARNING! Settings have been modified');
    set(handles.ValidityResults,'Backgroundcolor',[1 0 0]);
end

%-----------------------------------------------------------------------------------%
% --- Executes on button press in toggleSource.
function toggleSource_Callback(hObject, eventdata, handles)
load_listbox(pwd,handles);
settingsModification(handles);
if get(handles.toggleSource,'Value') == 0
    set(handles.toggleSource,'String','.wav files');
    set(handles.mainButton,'Visible','Off');    
else
    set(handles.toggleSource,'String','Waveforms generator');
    set(handles.mainButton,'Visible','ON');
end



%-----------------------------------------------------------------------------------%
% --- Executes on selection change in LFgenSelection.
function LFgenSelection_Callback(hObject, eventdata, handles)
settingsModification(handles);

switch get(handles.LFgenSelection,'Value')
    case 1
        sineLFGenParamVisibility(handles);
    case 2
        rectLFGenParamVisibility(handles);
    case 3
        NRZ_LFGenParamVisibility(handles);
    otherwise
        NoiseLFgenParamVisibility(handles);
end


% --- Executes during object creation, after setting all properties.
function LFgenSelection_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function LFgenLevel_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function LFgenLevel_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function LFgenOffset_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function LFgenOffset_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function LFgenFrequency_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function LFgenFrequency_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
function LFgenPeriods_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function LFgenPeriods_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function LFgenParam_4_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function LFgenParam_4_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function LFgenParam_5_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function LFgenParam_5_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function LFgenParam_6_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function LFgenParam_6_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%-----------------------------------------------------------------------------------%
function sineLFGenParamVisibility(handles)

set (handles.LFgenOffsetTxt,'String','Offset');
set (handles.LFgenOffset,'String','0');
set (handles.LFgenFrequency,'Visible','On');
set (handles.LFgenFreqTxt,'Visible','On');
set (handles.LFgenPeriods,'Visible','On');
set (handles.LFgenPeriodsTxt,'Visible','On');
set (handles.LFgenParam_4_Txt,'Visible','Off');
set (handles.LFgenParam_4,'Visible','Off');
set (handles.LFgenParam_5_Txt,'Visible','Off');
set (handles.LFgenParam_5,'Visible','Off');
set (handles.LFgenParam_6_Txt,'Visible','Off');
set (handles.LFgenParam_6,'Visible','Off');

%-----------------------------------------------------------------------------------%
function rectLFGenParamVisibility(handles)

set (handles.LFgenOffsetTxt,'String','Offset');
set (handles.LFgenOffset,'String','0');
set (handles.LFgenFrequency,'Visible','On');
set (handles.LFgenFreqTxt,'Visible','On');
set (handles.LFgenPeriods,'Visible','On');
set (handles.LFgenPeriodsTxt,'Visible','On');
set (handles.LFgenParam_4_Txt,'Visible','On');
set (handles.LFgenParam_4_Txt,'String','Rise time (s)');
set (handles.LFgenParam_4,'Visible','On');
set (handles.LFgenParam_4,'String','0');
set (handles.LFgenParam_5_Txt,'Visible','On');
set (handles.LFgenParam_5_Txt,'String','Fall time (s)');
set (handles.LFgenParam_5,'Visible','On');
set (handles.LFgenParam_5,'String','0');
set (handles.LFgenParam_6_Txt,'Visible','On');
set (handles.LFgenParam_6_Txt,'String','Width (s)');
set (handles.LFgenParam_6,'Visible','On');

%-----------------------------------------------------------------------------------%
function NRZ_LFGenParamVisibility(handles)

set (handles.LFgenOffsetTxt,'String','Offset');
set (handles.LFgenOffset,'String','0');
set (handles.LFgenFrequency,'Visible','On');
set (handles.LFgenFreqTxt,'Visible','On');
set (handles.LFgenPeriods,'Visible','On');
set (handles.LFgenPeriodsTxt,'Visible','On');
set (handles.LFgenParam_4_Txt,'Visible','On');
set (handles.LFgenParam_4_Txt,'String','States/symb.');
set (handles.LFgenParam_4,'Visible','On');
set (handles.LFgenParam_4,'String','2');
set (handles.LFgenParam_5_Txt,'Visible','Off');
set (handles.LFgenParam_5,'Visible','Off');
set (handles.LFgenParam_6_Txt,'Visible','Off');
set (handles.LFgenParam_6,'Visible','Off');

%-----------------------------------------------------------------------------------%
function NoiseLFgenParamVisibility(handles);

set (handles.LFgenOffset,'String','100000');
set (handles.LFgenOffsetTxt,'String','Nbr of points');
set (handles.LFgenFrequency,'Visible','Off');
set (handles.LFgenFreqTxt,'Visible','Off');
set (handles.LFgenPeriods,'Visible','Off');
set (handles.LFgenPeriodsTxt,'Visible','Off');
set (handles.LFgenParam_4_Txt,'Visible','Off');
set (handles.LFgenParam_4,'Visible','Off');
set (handles.LFgenParam_5,'Visible','Off');
set (handles.LFgenParam_5_Txt,'Visible','Off');
set (handles.LFgenParam_6_Txt,'Visible','Off');
set (handles.LFgenParam_6,'Visible','Off');

%-----------------------------------------------------------------------------------%
function [h] = firFilter(minFreq,maxFreq,hDuration,sampleFreq,windowType,handles)
% Computes the impulse time response filter based on a rectangular frequency response 
% with "baseBdWidth" frequency bandwidth. The impulse time response is then windowed
% by one of the following windows:
% Hanning, Hamming, Blackman.
% minFreq,maxFreq are the frequencies boundaries of the UNILATERAL bandpass spectrum obtained  
% after the filter operation. 
% In case of lowpass filter, choose minFreq = -maxFreq; don't forget that h will be
% affected by a factor 2 to take into account in the filtering operation.
% hDuration is the time duration of impulse response expressed in 1/baseBdWidth unit.

baseBdWidth = maxFreq - minFreq;    % Bandwidth of rectangular frequency response
freqShift = (maxFreq + minFreq)/2;  % Frequency shift if band pass filter required

Nk = floor(hDuration*sampleFreq/baseBdWidth);
if mod(Nk,2) == 0
    Nk = Nk + 1;
end
    
% Cardinal-sinus impulse response calculation
k = 1:(Nk-1)/2;
h = sin(pi*baseBdWidth*k/sampleFreq)./(pi*baseBdWidth*k/sampleFreq);
h = [fliplr(h) 1 h]*baseBdWidth/sampleFreq;
k = -(Nk-1)/2:(Nk-1)/2;

% Windowing the impulse response

switch windowType
    case 'Hanning'  % Hanning window
        window = 0.5*(1- cos(2*pi*[0:length(k)-1]/Nk));  
    case 'Hamming'  % Hamming window
        window = 0.54 - 0.46*cos(2*pi*[0:length(k)-1]/Nk);
    case 'Blackman' % Blackman window
        window = 0.42 -0.5*cos(2*pi*[0:length(k)-1]/Nk) ...
   + 0.08*cos(4*pi*[0:length(k)-1]/Nk);                   
    otherwise
        return
end
h = h.* window;
h = 2*h.*cos(2*pi*k*freqShift/sampleFreq);   % Frequency shift

%-----------------------------------------------------------------------------------%
function CarrierSampFactIn_Callback(hObject, eventdata, handles)
settingsModification(handles);

% --- Executes during object creation, after setting all properties.
function CarrierSampFactIn_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
function SourceSampFactorIn_Callback(hObject, eventdata, handles)
settingsModification(handles);
% --- Executes during object creation, after setting all properties.
function SourceSampFactorIn_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%-----------------------------------------------------------------------------------%
% --- Executes on button press in SourceFreqControlValidation.
function SourceFreqControlValidation_Callback(hObject, eventdata, handles)
settingsModification(handles);


%-----------------------------------------------------------------------------------%
% --- Executes on button press in PLLOutputFilter.
function PLLOutputFilter_Callback(hObject, eventdata, handles)
settingsModification(handles);
if get(handles.PLLOutputFilter,'Value') == 0
    set(handles.PLLOutputFilter,'String','PLL output filter ON');
else
    set(handles.PLLOutputFilter,'String','PLL output filter OFF');
end

%-----------------------------------------------------------------------------------%
% --- Executes on button press in EnableDemodButton.
function EnableDemodButton_Callback(hObject, eventdata, handles)
settingsModification(handles);

%-----------------------------------------------------------------------------------%
function DemodSetting_2_Callback(hObject, eventdata, handles)
settingsModification(handles);

%-----------------------------------------------------------------------------------%
function MatlabModulestoggle_Callback(hObject, eventdata, handles)
settingsModification(handles);
if get(handles.MatlabModulestoggle,'Value') == 0
    set(handles.MatlabModulestoggle,'String','No toolbox in use');
else
    set(handles.MatlabModulestoggle,'String','Signal processing toolbox required');
end


%-----------------------------------------------------------------------------------%
function [envelope modltCarrier]= ...
    VeawerSSB(upDown,basebandIn,fstCarrierFreq,channelCarrierFreq,magCarriers,sampleFreq,time,handles)

envelope = basebandIn; % Improper designation here but easy for future plot 
if get(handles.MatlabModulestoggle,'Value') == 0
    num =firFilter(-fstCarrierFreq,fstCarrierFreq,30,sampleFreq,'Blackman',handles);
    den = 1;
else
    [num,den] = ellip(7,1,60,2*fstCarrierFreq/sampleFreq);
end

Env_I = filter (num,den,basebandIn.* (magCarriers*cos(2*pi*fstCarrierFreq.*time'))); % Complex envelope chanel I
Env_Q = filter (num,den,basebandIn.* (magCarriers*sin(2*pi*fstCarrierFreq.*time'))); % complex envelope chanel Q
I = Env_I .* (magCarriers*cos(2*pi*(channelCarrierFreq + upDown*fstCarrierFreq).*time'));
Q = Env_Q .* (magCarriers*sin(2*pi*(channelCarrierFreq + upDown*fstCarrierFreq).*time'));
if upDown == 1
    modltCarrier = -(I + Q);  % SSB-USB
else
    modltCarrier = I - Q;     % SSB-LSB
end


%-----------------------------------------------------------------------------------%
function [modltCarrier] = ...
    RF_VSB(upDown,Nslope_min,basebandIn,channelCarrierFreq,magCarrier,sampleFreq,time,handles)
% Rem : upDown variable must be 1 (VSB-USB) or -1 (VSB-LSB).
%       Nslope_min  is the minimum number of elements for frequency slope of frequency
%       response around Fp
%___________________________________________________________________________________%
%   |
%   1|..................#######################
%   |                  #                      #       
%   |                 #                       #
%   |                #                        #
% ##0################ ------------------------##########//#############----------> F
%   |              /  |   \                   |                       |
%   0.........Fp-Fv...Fp...Fp+Fv..........Fp + Fs_max................sampleFreq
%   0................................................................NFFT-1
%___________________________________________________________________________________%


% Evaluate the number of point to be used for impulse channel filter response
alpha  = str2double(get(handles.modParam,'String'))/100;
Fs_max = str2double(get(handles.maxFreq,'String'));
if alpha >= 1
    errordlg('Vestigial band too large','Value error')
end
p = ceil(log((Nslope_min-1)*sampleFreq/(2*Fs_max*alpha))/log(2)); % NFFT = 2^p points
NFFT = 2^p;         % Number of fft points separated by sampleFreq/NFFT
Nslope = ceil(2*alpha*Fs_max*NFFT/sampleFreq); % Number of point adjustment about frequency 
% slope response.
if mod(Nslope,2) == 0 % Make the frequency response slope odd in number of points.
    Nslope = Nslope +1;
end

% VSB filter frequency response 

Fs_max = str2double(get(handles.maxFreq,'String'));
a = ceil(Fs_max*NFFT/sampleFreq) - (Nslope-1)/2;
H_rf = [[0:1/(Nslope-1):1] ones(1,a)];

if upDown == 1
    H_rf = [zeros(1,floor(channelCarrierFreq*NFFT/sampleFreq)-(Nslope-1)/2) H_rf]; % VSB-USB
else
    H_rf = [zeros(1,floor(channelCarrierFreq*NFFT/sampleFreq)-(Nslope-1)/2 -a) fliplr(H_rf)]; % VSB-LSB
end
H_rf = [H_rf zeros(1,NFFT-length(H_rf))];

% Temporal response of VSB filter 
h_rf = ifft(H_rf);
h_rf = fftshift(h_rf);
h_rf = real(h_rf);
window = 0.42 -0.5*cos(2*pi*[0:NFFT-1]/NFFT) ...
   + 0.08*cos(4*pi*[0:NFFT-1]/NFFT); % Apply Blackman window
h_rf = h_rf.*window;

% VSB carrier modulation  
modltCarrier = 4*basebandIn.*(magCarrier*cos(2*pi*channelCarrierFreq.*time'));
modltCarrier = filter(h_rf,1,modltCarrier);



%-----------------------------------------------------------------------------------%
function [Output] = pulseAverage...
    (Input,B_expandFactor,maxFreqDeviation,sourceMaxFreq,carrierFreq,Fsample,handles)

% Principle of operation: to create a train of pulses of constant width "Theta" with 
% one pulse by period of demodulated carrier. The pulses appear when carrier crosses 
% a pre-defined threshold ( zero in this case ). Time between two rising (or falling) 
% edges of two consecutive pulses - correctly calibrated in duration - is relative to 
% instantaneous frequency of the carrier to be demodulated. Thus, the mean value of 
% this pulses train is representative of the information transmitted by frequency mo-
% -dulation.
% For pulses limited between 0 and 1 and When working directly with received carrier
% with frequency Fp, the averaged output "d" follows this relation:
%
%     0<= Theta.(1-maxFreqDeviation/Fp)<= d <= Theta.(1-maxFreqDeviation/Fp) <= 1
%
% In real systems, the ratio "1-maxFreqDeviation/Fp" is often very small compared to
% 1. Thus, in these cases the dynamic slope of the output demodulator is too small. One 
% way to improve it is to translate the received spectrum toward lower
% frequencies replacing in the above relationship Fp by F2 < Fp. This is the method used in this
% function. 
% The function estimates the occupied bandwidth "B" of the modulated received carrier
% ( Carson band enlarged by a factor "B_expandFactor" ) and then F2=B.


time=[1:numel(Input)]/Fsample;     % Time vector
F2=  B_expandFactor*(maxFreqDeviation + sourceMaxFreq); % Demodulator center frequency.

% test if error exists in relative frequencies values 
if (carrierFreq - F2) < 0
    errordlg('Carrier frequency value is too small','Value error')
    Output = ones(size(Input)); % Dummy values for Output due to error
    return
end

% Downconverts the received signal toward F2 center frequency.
Input = Input.*cos(2*pi*(carrierFreq - F2).*time'); 
Fc_Rx = F2+maxFreqDeviation+sourceMaxFreq;
if get(handles.MatlabModulestoggle,'Value') == 0
    num =0.5*firFilter(-Fc_Rx,Fc_Rx,30,Fsample,'Blackman',handles);
    den = 1;
else
    [num,den] = cheby1(7,1,2*Fc_Rx/Fsample);
end
Input = filter (num,den,Input); % Suppression of sum term of temporal multiplication.

% Build the calibrated pulses received signal.
k = 0.5; % Limitation of pulses durations ( must be <= 1 and tested )
Theta = floor(k*Fsample/(F2 + maxFreqDeviation));   % Theta duration assesment; 
                                                    % unit: sample period
In_Demod_B = sign(Input - 0.1*std(Input));
In_Demod_B = [diff(In_Demod_B);0]>0;
In_Demod_B1 = In_Demod_B;

In_Demod_B_Delayed =In_Demod_B;
for i =1:Theta % Build the Theta wide pulses train
    In_Demod_B_Delayed =[0 ; In_Demod_B_Delayed(1:numel(In_Demod_B_Delayed)-1)];% One sample time shift
    In_Demod_B = In_Demod_B + In_Demod_B_Delayed;
end
In_Demod_B = double(In_Demod_B > 0);

% Average the pulses train
if get(handles.MatlabModulestoggle,'Value') == 0
    num =0.5*firFilter(-sourceMaxFreq,sourceMaxFreq,10,Fsample,'Blackman',handles);
    den = 1;
else
    [num,den] = ellip(7,1,80,2*sourceMaxFreq/Fsample);;
end

Output = filter (num,den,In_Demod_B);
Output = (Output-mean(Output));


%-----------------------------------------------------------------------------------%
function [output] = PLLdemod (Input,VCO_Magnitude,sourceMaxFreq,Fsample,handles)

% The idea is to use a "VCO" who follows by servo-control the instantaneous frequency
% in received FM modulated carrier. The output signal representative of source
% information is contained in scaled driving level of this "VCO". The loop used hier 
% is a second order loop with closed transfer function:
%                   
%   output     1                     1
%   ------ =  ---.----------------------------------------
%     Fin      kv           1                tau
%                  1 + -------------.s + -------------.s^2 
%                       2.pi.kphi.kv      2.pi.kphi.kv
%
% Fin: instantaneous frequency of received carrier
% kphi: phase comparator gain ( level unit/radian
% kv : VCO slope (Hz/level unit)                                       1
% tau: first order loop low pas filter with transfer function: H = ---------
%                                                                  1 + tau.s
%
% Loop control parameters are:
% - Fn : natural frequency of closed transfer function.
% - ksi: damping factor     "    "       "        " .
% Because computing time in relation with sometimes long lengths of used variables
% the analog response of the loop filter is approximated in sample time by Euler
% method (d(S(t)/dt ----> [S(k) - S(k-1)]/ sampleTime).
%
 


inputMag = std(Input);
%kphi = 1/pi;                                          % XOR used as a phase comparator
kphi = 0.5*VCO_Magnitude*inputMag;                     % Multiplier used as a phase comparator
Fn = str2double(get(handles.DemodSetting_2,'String')); % natural loop cut-off frequency
Ksi = str2double(get(handles.DemodSetting_1,'String'));
tau = 1/(4*Ksi*pi*Fn);              % Time constant of first order lowpass loop filter
fvco= str2double(get(handles.carrierFreq,'String')); % Quiescent VCO frequency is Fp

kv=Fn/(2*Ksi*kphi);                 % Loop VCO slope
a = tau*Fsample;
b = a+1;

outCP = zeros(size(Input));         % Phase comparator output
output= zeros(size(Input));         % Loop filter output
outVCOLoop = zeros(size(Input));    % loop VCO output
phaseVCOLoop = 0 ;                  % Loop VCO initial phase


% Loop samples computation
for i = 2:length(Input)
    %outCP(i,1) = double(xor((Input(i,1)>0) , (outVCOLoop(i-1,1)>0)))-0.5; % XOR
    outCP(i,1) = Input(i,1) * outVCOLoop(i-1,1); % Multiplier
    output(i,1) = (outCP(i,1)+ a*output(i-1,1))/b;
    phaseVCOLoop = mod(phaseVCOLoop + 2*pi*(fvco + kv*output(i,1))/Fsample,2*pi);
    outVCOLoop(i,1) = VCO_Magnitude*cos(phaseVCOLoop);
end % end for

if get(handles.PLLOutputFilter,'Value') == 0
    if get(handles.MatlabModulestoggle,'Value') == 0
        num =0.5*firFilter(-sourceMaxFreq,sourceMaxFreq,10,Fsample,'Blackman',handles);
        den = 1;
    else
        [num,den] = butter(3,2*sourceMaxFreq/Fsample); % Low pass filter
    end
    output = filter (num,den,output);
end
% Scale the demodulated signal
output = output*kv/str2double(get(handles.modParam,'String')); % Level scaling in 
% order to facilitate the comparison between source and demodulated signal ( see
% results panel ).



%-----------------------------------------------------------------------------------%
function [errFlag PSD freq] = myPSD(input,NFFT,Fsample,handles)
% Compute and average periodogramms of NFFT length.

if length(input) < 2*NFFT
    errordlg('There is not enough points in signal compared to FFT length ','Value error')
    PSD = 0;
    freq = 0;
    errFlag = 1;
    return
end
errFlag = 0;
input = input(1:floor(length(input)/NFFT)*NFFT,1);
input = reshape (input,NFFT,numel(input)/NFFT);
a = size(input);
% window = 0.54 - 0.46*cos(2*pi*[0:NFFT-1]/NFFT);
% window = repmat(window',1,a(1,2));
% input = input.*window;
PSD = (abs(fft(input))/NFFT).^2;
PSD = sum(PSD')/a(1,2);
PSD = fftshift(PSD);
freq = [-NFFT/2: 0 1:NFFT/2-1]*Fsample/NFFT;





Contact us at files@mathworks.com