%% XilinxFIRCoeffiecientsCreatator.m
%% Copyright (c) 2012, Jay Kickliter [ http://www.kickliter.com ], [ jay@kickliter.com ]
%% You are free to whatever you wish with is code.
%
%% This Octave script takes your low pass filter data and
%% creates a Xilinx '.coe' file for use in their FIR compiler.

% _   _ ____ _  _ ____    ____ _ _    ___ ____ ____ 
%  \_/  |  | |  | |__/    |___ | |     |  |___ |__/ 
%   |   |__| |__| |  \    |    | |___  |  |___ |  \ 
%                                                   
% ____ ___  ____ ____ _ ____ _ ____ ____ ___ _ ____ _  _ ____ 
% [__  |__] |___ |    | |___ | |    |__|  |  | |  | |\ | [__  
% ___] |    |___ |___ | |    | |___ |  |  |  | |__| | \| ___] 
                                                          
sample_rate    = 44100;                             % sampling rate
cutoff_freq    = 12000;                             % cutoff frequency
filter_size    = 121;                               % filter size - 1. the filter will be one coefficient larger than the number you enter here
scaling_factor = 2^15-1;                            % scale the factor if you are working with integer or fixed-point coeficcients
output_file    = '/Users/jaykickliter/Dropbox/Projects/Xilinx/ADC_to_DAC/filter_coeficcients.coe';

% _  _ ____    _  _ ____ ____ ___     ___ ____    ____ ___  _ ___ 
% |\ | |  |    |\ | |___ |___ |  \     |  |  |    |___ |  \ |  |  
% | \| |__|    | \| |___ |___ |__/     |  |__|    |___ |__/ |  |  
%                                                                 
% ___  ____ _    ____ _ _ _ 
% |__] |___ |    |  | | | | 
% |__] |___ |___ |__| |_|_| 
%                           

fd             = fopen(output_file, 'w');           % open or create the output file
fclear(fd);                                         % erase previous contents

nyquist_freq   = sample_rate/2;                     % nyquist frequency
nyquist_cutoff = cutoff_freq/nyquist_freq;          % cutoff frequency 
b              = fir1(filter_size, nyquist_cutoff); % create the filter
b              = round(b.*scaling_factor);          % scale the filter coeficcients

fprintf(fd, 'radix    = 10;\n');
fprintf(fd, 'coefdata = ');
fprintf( fd, '%d', b(1));
for ii = 1:length(b);
  fprintf( fd, ',% d', b(ii));
end
fprintf(fd, ';');

fclose(fd);
