⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rtdxlmsdemo_script.m

📁 matlab连接ccs的例子
💻 M
字号:
function dummy = rtdxlmsdemo_script(boardNum, procNum, varargin)
%RTDXLMSDEMO_SCRIPT Run RTDX(tm) automation demo.
%   DUMMY = RTDXLMSDEMO_SCRIPT(BOARD,PROC,FILTERORDER,FRAMESIZE,NUMFRAMES)
%   demonstrates the use of RTDX methods to transfer data between MATLAB and the
%   target TI(tm) DSP.  The target application adaptively cancels broadband 
%   noise by employing a normalized LMS algorithm.
%    
%   Unfiltered noise data along with the signal plus low-pass filtered noise 
%   data are transfered to the target DSP by employing RTDX object methods.
%   The target DSP applies the adaptive LMS algorithm and sends back to the 
%   MATLAB workspace the estimated low-pass filter taps at each iteration along 
%   with the streaming filtered time series data.
%
%   Plots include the incremental tap updates and frequency responses, and time
%   series data of signal, signal plus noise, and the filtered signal plus 
%   noise.
%
%   This function connects to the target DSP specified by the board number, 
%   BOARD, and processor number, PROC.  The lengths of the tapped delay lines 
%   for the low pass FIR and the nLMS filter are identically specified by 
%   FILTERORDER.  The frame size is specified by FRAMESIZE, and the number of 
%   frames to process by NUMFRAMES.
%
%   DUMMY = RTDXLMSDEMO_SCRIPT(BOARD,PROC,FILTERORDER,FRAMESIZE) is the same as 
%   the above calling syntax with NUMFRAMES defaulting to 1.
%
%   DUMMY = RTDXLMSDEMO_SCRIPT(BOARD,PROC,FILTERORDER) is the same as above with
%   FRAMESIZE defaulting to 256.
%
%   DUMMY = RTDXLMSDEMO_SCRIPT(BOARD,PROC) is the same as above with FILTERORDER
%   defaulting to 32.

%   Copyright 2002 The MathWorks, Inc.
%   $Revision: 1.18 $  $Date: 2002/03/29 00:32:21 $

% Generate broadband noise vector (filter input)

% Parse and validate the inputs
[errMsg, filterOrder, frameSize, numFrames] = ...
    parse_args(boardNum, procNum, varargin{:});
error(errMsg);

% Following defaults apply, if not specified

% filterOrder = 32;
% frameSize = 256;
% numFrames = 2

% Create signal and noise vectors
startN(1) = 1;
startD(1) = 1;
stopN(1) = frameSize;
stopD(1) = frameSize+filterOrder-1;

for i=2:numFrames,
    startN(i) = stopN(i-1)+1;
    stopN(i) = startN(i)+frameSize-1;
    startD(i) = stopD(i-1)+1;
    stopD(i) = startD(i)+frameSize-1;
end

outBuf = frameSize;  % coeff buffer size
noise = randn(1,frameSize*numFrames);
maxVal = max([max(noise) abs(min(noise))]);
shiftBits = 15-nextpow2(maxVal)-2;
scale = 2^(shiftBits);

noise_int16 = double2int16(noise, scale);

% Set up filter response window:
[filtWin, hFig] = SetupFilterPlot(filterOrder);

% Filter broadband noise
cutOffFreq = 0.5;
filteredNoise = demo_fir(filterOrder, cutOffFreq, noise);
filteredNoise_int16 = double2int16(filteredNoise, scale);

% Generate 440 Hz pure tone signal
f=440; fs=8000; t=0:(frameSize*numFrames)+filterOrder-2;
CW = sin(2*pi*f*t/fs);
CW_int16 = double2int16(CW, scale);

% Signal + filtered noise
S_N = CW + filteredNoise;
S_N_int16 = double2int16(S_N, scale);

% Construct code composer/rtdx object
cc=ccsdsp('boardnum',boardNum,'procnum',procNum);
pause(2.0);

% Make sure selected processor is RTDX-compatible
% ========================================================================
if cc.isrtdxcapable,
    if (cc.info.subfamily >= hex2dec('50')) & ...
            (cc.info.subfamily <= hex2dec('5f')),
        c5x = logical(1);
        target_subdir = 'c5x';
        outFile = 'rtdxdemo_5x.out';
    elseif (cc.info.subfamily  >= hex2dec('60')) & ...
            (cc.info.subfamily  <= hex2dec('6f')),
        c5x = logical(0);
        if cc.info.revfamily > 10,
            target_subdir = 'c6x';  
            outFile = 'rtdxdemo_6x1x.out';
        else
            target_subdir = 'c6x';
            outFile = 'rtdxdemo_6x0x.out';
        end
    else % Selected processor is not a C5xxx nor C6xxx
        uiwait(msgbox({'RTDX is not supported for the selected board,  '; 
            'please select another board.'},...
            'Selection Error','modal'));
        clear cc;
        close(hFig);
        return
    end
else % Selected processor is a Simulator
    uiwait(msgbox({'RTDX is not supported for the Simulator,  ';
        'please select another board.'},...
        'Selection Error','modal'));
    clear cc;
    close(hFig);
    return
end
%===========================================================================

% Change directory to target demo directory and
%   Open target file
target_dir = fullfile(matlabroot,'toolbox','ccslink','ccsdemos','rtdxlms',...
    target_subdir);
cc.cd(target_dir)

fprintf('Loading COFF file to target DSP...\n');
try
    cc.reset
    pause(0.5)
    cc.load(outFile)
catch
    % close Figure, and display error
    clear cc;
    close(hFig);
    errordlg({'There is a problem loading the COFF file for the selected processor.';...
            'You may need to rebuild project with appropriate linker command file.'},...
        'Load Error' , 'modal');
    return
end

% Configure channel buffers
cc.rtdx.configure(10000,4);   % define 4 channels buffers of 1024 bytes each

fprintf('Opening RTDX channels...\n');
% Open write channel
cc.rtdx.open('ichan0','w','ichan1','w');

% Open read channels
cc.rtdx.open('ochan0','r');

% Enable all open channels
cc.rtdx.enable('all');

% Enable RTDX
cc.rtdx.enable;

% Overwrite global timeout value
cc.rtdx.set('timeout', 30)            % 30 seconds

% Display channel information
cc.rtdx

% Write to filter parameters to target DSP
fprintf('Writing filter parameters to target...\n\n');
filtParms=[filterOrder frameSize numFrames shiftBits];
cc.rtdx.writemsg('ichan0', int16(filtParms));

for ct = 1:numFrames,
    % Write to target DSP
    fprintf('Writing noise and signal + noise to target - frame %d...\n',ct);
    cc.rtdx.writemsg('ichan0', noise_int16(startN(ct):stopN(ct)));
    cc.rtdx.writemsg('ichan1', S_N_int16(startD(ct):stopD(ct)));
end
fprintf('\n');

% Run target
fprintf('Running target application...\n\n');
cc.run;

outError=zeros(1,frameSize);
s=PlotSignalIO(outError,CW,S_N);

yLines = [s.FiltOut s.SigPlusNoise s.Input];
allNaN = NaN*ones(1,frameSize);
set(yLines, ...
    'EraseMode', 'xor', ...
    'xdata',1:frameSize, ...
    'ydata',allNaN);
    
for ct = 1:numFrames,
    % Reset display to all NaN at start of each frame:
    set(yLines, 'ydata', allNaN);
    
    fprintf(['Reading coefficient updates and filtered results from '...
            'target - frame %d...\n'],ct);
    
    numPerBlock = outBuf/filterOrder;
    numBlocks   = frameSize/numPerBlock;
    
    for i=1:numBlocks,
        outCoeff_int16 = cc.rtdx.readmsg('ochan0', 'int16');
        outCoeff = int16todouble(outCoeff_int16,scale);
        
        for j=1:numPerBlock,
            startIdx = (j-1)*filterOrder+1;
            endIdx = startIdx + filterOrder-1;
            set(filtWin.hTaps, 'ydata',fliplr(outCoeff(startIdx:endIdx)));
            
            ff = fft(fliplr(double(outCoeff(startIdx:endIdx))), 256);
            ff = 20*log10(abs(ff(1:128)));
            fmax = max(ff);
            set(filtWin.hFreq, 'ydata', ff-fmax);
        end
        
        if ~c5x,
            % Update signal plots
            %
            % Get signal indices:
            x=(i-1)*numPerBlock+1;
            y=(i-1)*numPerBlock+numPerBlock;
            xx = x + (ct-1)*frameSize;
            yy = y + (ct-1)*frameSize;
            %
            % Update plot data: 
            yAll=get(yLines,'ydata');
            yAll{1}(x:y) = int16todouble(cc.rtdx.readmsg('ochan0', 'int16'),scale);
            yAll{2}(x:y) = S_N(xx:yy);
            yAll{3}(x:y) = CW(xx:yy);
            set(yLines,{'ydata'},yAll);
            drawnow;
        end
    end
    if c5x, % plot frame of time-series
        yAll=get(yLines,'ydata');
        yAll{1} = int16todouble(cc.rtdx.readmsg('ochan0', 'int16'),scale);
        yAll{2} = S_N(1:frameSize);
        yAll{3} = CW(1:frameSize);
        set(yLines,{'ydata'},yAll);
        drawnow;
    end
    
end

% Disable all open channels
cc.rtdx.disable('all');

% Disable RTDX
cc.rtdx.disable;

% Close channels
cc.rtdx.close('all');

clear cc;   % Call destructors

fprintf('\n**************** Demo complete. ****************\n\n');


%------------------------------------------------------------------------------
function [errMsg, filterOrder, frameSize, numFrames] = ...
    parse_args(boardNum, procNum, varargin)
% Parse and validate the inputs
% 'msg' is empty if no error occurs.

filterOrder  = [];
frameSize    = [];
numFrames    = [];

errMsg = nargchk(2,5,nargin);
if ~isempty(errMsg), return; end

if ~(isnumeric(boardNum)&isreal(boardNum)&(boardNum>=0)),
    errMsg = 'Board number must be zero or a positive integer';
    return
end

if ~(isnumeric(procNum)&isreal(procNum)&(procNum>=0)),
    errMsg = 'Board number must be zero or a positive integer';
    return
end

if nargin >= 3,
    if (varargin{1} == 16)|(varargin{1} == 32)|(varargin{1} == 64),
        filterOrder = varargin{1};
    else
        errMsg = 'Filter order must be 16, 32, or 64';
    end
    if nargin >= 4,
        if (varargin{2} == 128)|(varargin{2} == 256)|(varargin{2} == 512),
            frameSize = varargin{2};
        else
            errMsg = 'Frame size must be 128, 256, or 512';
        end
        if nargin == 5,
            if (varargin{3} == 1)|(varargin{3} == 2)|(varargin{3} == 4),
                numFrames = varargin{3};
            else
                errMsg = 'Number of frames must be 1, 2, or 4';
            end
        else
            numFrames = 2;
        end
    else
        numFrames = 2;
        frameSize = 256;
    end
else
    numFrames = 2;
    frameSize = 256;
    filterOrder = 32;
end    

%------------------------------------------------------------------------------
function out = double2int16(data,scaleFactor);

out = int16(round(data*scaleFactor));


%------------------------------------------------------------------------------
function out = int16todouble(data,scaleFactor);

out = double(data)/scaleFactor;


%------------------------------------------------------------------------------
function out = demo_fir(order,cutoff,data);

coeff = fir1(order-1,cutoff);
out = conv(coeff,data);


%------------------------------------------------------------------------------
function [s, hFig] = SetupFilterPlot(filterOrder)
%SetupFilterResponse
% Returns a structure with:
%   .hTaps
%   .hFreq

% Check for existing figure window
filtTag = 'rtdxlmsdemo_filters';
signalTag = 'rtdxlmsdemo_signal';

s=[];

hFig = findobj('tag',filtTag);
if ~isempty(hFig),
    close(hFig);
end

hFig1 = findobj('tag',signalTag);
if ~isempty(hFig1),
    close(hFig1);
end

hFig = figure(...
    'numbertitle','off', ...
    'name','rtdxlmsdemo - Filter Results', ...
    'IntegerHandle','off', ...
    'units','normalized', ...
    'tag', filtTag, ...
    'pos',[0.01 0.47 0.35 0.45]);

% Setup tap axis
subplot(2,1,1); grid on;
title('Tap Coefficients');
s.hTaps=line;
set(s.hTaps, ...
    'erase','xor', ...
    'color','r');
a = gca;
set(a,'ylim',[-0.2 0.6]);
set(a,'xlim',[0 filterOrder]);

set(get(a,'title'),'fontsize',11);
set(a,'fontsize',8);
set(a,'fontweight','light') ;

% Setup freq axis
subplot(2,1,2); grid on;
title('Filter Response');
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
s.hFreq=line;
set(s.hFreq, ...
    'erase','xor', ...
    'color','r');
b = gca;
set(b,'ylim',[-40 0]);
set(b,'xlim',[0 4000]);

set(get(b,'title'),'fontsize',11);
set(b,'fontsize',8);
set(b,'fontweight','light') ;
x = get(b,'xlabel');
set(x,'fontsize',8);
set(x,'fontweight','light');
y = get(b,'ylabel');
set(y,'fontsize',8);
set(y,'fontweight','light');

set(hFig,'userdata',s);  % Retain structure in figure's UserData field

% Initialize lines
set(s.hTaps, 'xdata',1:filterOrder,    'ydata',zeros(1,filterOrder));
set(s.hFreq, 'xdata',(0:127)/127*4000, 'ydata',zeros(1,128));

figure(hFig);
drawnow;


%------------------------------------------------------------------------------
function s = PlotSignalIO(outError, CW, S_N)
%PlotSignalIO

% Check for existing figure window
signalTag = 'rtdxlmsdemo_signal';
s = [];


hFig = figure( ...
    'numbertitle','off', ...
    'name','rtdxlmsdemo - Signals', ...
    'IntegerHandle','off', ...
    'tag', signalTag, ...
    'units','normalized', ...
    'menubar','Figure', ...
    'pos', [0.37 0.28 0.44 0.64]); 
hax = axes('parent',hFig, ...
    'pos', [0.13 0.701222343126587 0.775 0.223777656873413], ...
    'xlim', [1 length(outError)], ...
    'ylim', [-2 2], ...
    'drawmode','fast', ...
    'xgrid', 'on', 'ygrid', 'on');

set(get(hax,'title'),'fontsize',11);
set(hax,'fontsize',8);
set(hax,'fontweight','light') ;
x = get(hax,'xlabel');
set(x,'fontsize',8);
set(x,'fontweight','light');
y = get(hax,'ylabel');
set(y,'fontsize',8);
set(y,'fontweight','light');

set(get(hax,'title'),'string','Input Signal');
set(get(hax,'ylabel'),'string','Amplitude');
s.Input = line('parent',hax, 'color','b');

hax = axes('parent', hFig, ...
    'pos', [0.13 0.405611171563293 0.775 0.223777656873413], ...
    'xlim', [1 length(outError)], ...
    'ylim', [-2 2], ...
    'drawmode','fast', ...
    'xgrid', 'on', 'ygrid', 'on');
set(get(hax,'title'),'string','Signal + Noise');
s.SigPlusNoise = line('parent',hax, 'color','b');

set(get(hax,'title'),'fontsize',11);
set(hax,'fontsize',8);
set(hax,'fontweight','light') ;
x = get(hax,'xlabel');
set(x,'fontsize',8);
set(x,'fontweight','light');
y = get(hax,'ylabel');
set(y,'fontsize',8);
set(y,'fontweight','light');

hax = axes('parent', hFig, ...
    'pos', [0.13 0.11 0.775 0.223777656873413], ...
    'xlim', [1 length(outError)], ...
    'ylim', [-2 2], ...
    'drawmode','fast', ...
    'xgrid', 'on', 'ygrid', 'on');
set(get(hax,'title'),'string','Filtered Output');
set(get(hax,'xlabel'),'string','Sample Number');
s.FiltOut = line('parent',hax, 'color','b');

set(get(hax,'title'),'fontsize',11);
set(hax,'fontsize',8);
set(hax,'fontweight','light') ;
x = get(hax,'xlabel');
set(x,'fontsize',8);
set(x,'fontweight','light');
y = get(hax,'ylabel');
set(y,'fontsize',8);
set(y,'fontweight','light');

set(hFig,'userdata',s);  % Retain structure in figure's UserData field

figure(hFig); 
drawnow;

% [EOF] rtdxlmsdemo_script.m

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -