%
% Copyright (C) 2004 by Hernán Ordiales
% <audiocode@uint8.com.ar>
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
function fast_conv( file, impulse, output )
% Fast convolution of an audio signal with the impulse response of a system modeled as LTI (Linear Time Invariant) one.
% USE: fast_conv( 'source.wav', 'impulse_response.wav', 'output.wav' );
h_stereo = true;
x_stereo = true;
clip_factor = 1.01; % clip factor default value
% impulse response:
[ h, Fs1 ] = wavread( impulse ); % 2 columns matrix, one per channel
h1 = h(:,1); % col 1 -> left channel
h_channels = size(h); h_channels = h_channels(2);
if( h_channels == 2 )
h2 = h(:,2); % col 2 -> right channel
else
h2 = h(:,1); % col 1 -> left channel
h_stereo = false;
end
% file to process:
[ x, Fs2 ] = wavread( file );
x1 = x(:,1); % col 1 -> left channel
x_channels = size(x); x_channels = x_channels(2);
if( x_channels == 2 )
x2 = x(:,2); % col 2 -> right channel
else
x2 = x(:,1); % col 1 -> left channel
x_stereo = false;
end
% if sample rates are the same
if( Fs1 == Fs2 )
% searches for the amount of points required to perform the FFT
L = length(h1) + length(x1) - 1; % linear convolution length
disp('Processing...');
% Use nextpow if you have it to replace below code -> N = 2^nextpow(L);
N = 2;
while( N<L ) % first 2 pow greater than L
N = N*2;
end
% Note: N>=L is needed because the IDFT of the multiplication is the circular convolution and to match it to the
% common one, N>=L is required (where L=N1+N2-1;N1=length(x);N2=length(h))
% FFT(X,N) is the N points FFT, with zero padding if X has less than N points and truncated if has more.
H1 = fft( h1, N ); % Fourier transform of the impulse
X1 = fft( x1, N ); % Fourier transform of the input signal
F_y1 = H1 .* X1; % spectral multiplication
y1 = ifft( F_y1 ); % time domain again
% audio normalization: if "y = y/max(y)" -> "values out of [-1,+1] range are clipped"
y1 = y1/( max(y1)*clip_factor ); % to avoid clipping
% if one of the files is stereo, process the other channel
if( h_stereo || x_stereo )
H2 = fft( h2, N ); % Fourier transform of the impulse
X2 = fft( x2, N ); % Fourier transform of the input signal
F_y2 = H2 .* X2; % spectral multiplication
y2 = ifft( F_y2 ); % time domain again
y2 = y2/( max(y2)*clip_factor ); % to avoid clipping
y = [ y1 y2 ]; % stereo output (two channels)
else
y = y1; % mono output
end
wavwrite( y, Fs1, output );
disp( 'Convolution success.' );
else
disp('Error: files has different sample rate.');
end
function [xd] = recorreder(x,N)
% This function shifts a vector by N positions to the right
% As posted in DSPrelated.com
% http://www.dsprelated.com/showcode/43.php
%
lx = length(x);
if N>lx
fprintf('N has to be smaller than the vector length');
return;
else
xd(N+1:lx) = x(1:lx-N);
end;
% Created by José David Valencia Pesqueira
% UPIITA-IPN 2010
% For the DWT chain-processing example
% as posted in DSPrelated.com
% http://www.dsprelated.com/showcode/44.php
%
function [hx] = formfilters(n_stages,branch,h0,h1)
p = branch;
% Seed vector
hx = 0;
hx(1) = 1;
switch n_stages
case 1
if mod(branch,2) ~= 0
hx = h0;
else
hx = h1;
end
case 2
switch branch
case 1
hx = conv(h0,upsample2(h0,2));
case 2
hx = conv(h0,upsample2(h1,2));
case 3
hx = conv(h1,upsample2(h0,2));
case 4
hx = conv(h1,upsample2(h1,2));
otherwise
beep;
fprintf('\nFor a 2-stage bank there cannot be a fifth branch');
end
otherwise
for i=0:n_stages-2
q = floor(p /(2^(n_stages-1-i)));
if (q == 1)
hx = conv(hx,upsample2(h1,2^i));
else
hx = conv(hx,upsample2(h0,2^i));
end
% p = mod(p,2^(n_stages-1-i)); %For DWPT
p = mod(2^(n_stages-1-i),p); %For DWT
end
t = mod(branch,2);
if(t == 1)
hx = conv(hx,upsample2(h0,2^(n_stages-1)));
else
hx = conv(hx,upsample2(h1,2^(n_stages-1)));
end
end
function plot_amp_spectrum(Fs, y, varargin)
%PLOT_AMP_SPECTRUM Plot amplitude spectrum of a one dimensional signal
% PLOT_AMP_SPECTRUM(FS, Y, COLOR, SEMILOG_SCALE, TITLE_STRING) plots the
% amplitude spectrum of y which has sampling frency Fs. Specification
% of color of the plot, wheather the plot is needed in semilog_scale or
% not, and the title string for the figure are OPTIONAL.
%
% Fs: Sampling frequency.
% y: Plots the one sided amplitude spectrum of the signal with,
% color: color of the plot specified in string,
% semilog_scale: [1]= Plot in log scale.
% Example:
% load ecg;
% plot_amp_spectrum(hz, signal); OR
% plot_amp_spectrum(hz, signal, 'r', 1) OR
% plot_amp_spectrum(hz, signal, 'r', 0, 'Amplitude spectrum of ECG signal')
%--------------------------------------------------------------------------
% Author: Aniket Vartak
% Email: aniket.vartak@gmail.com
% This function uses Matlab's fft() function, and builds on top of it to give
% a handy interface to get a nicely formatted plot of the amplitude
% spectrum.
%--------------------------------------------------------------------------
% Specify the default string incase its not provided
default_title_string = 'Single-Sided Amplitude Spectrum of y(t)';
%Deal with variable number of inputs after fs and x.
if(isempty(varargin)) % No optional information provided
color = 'b';
semilog_scale = 0;
title_string = default_title_string;
end;
if(length(varargin) == 1) % Only color info provided
color = varargin{1};
semilog_scale = 0;
title_string = default_title_string;
end;
if(length(varargin) == 2) % color and integer indicating semilog plot is needed is provided
color = varargin{1};
semilog_scale = varargin{2};
title_string = default_title_string;
end;
if(length(varargin) == 3) % All optional info provided
color = varargin{1};
semilog_scale = varargin{2};
title_string = varargin{3};
end;
%--------------------------------------------------------------------------
T = 1/Fs; % Sample time
L = max(size(y)); % Length of signal
NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L; % Take the fourier transform
f = Fs/2*linspace(0,1,NFFT/2+1);% Space out the frequencies
set(gcf, 'Name', strcat('Amplitude Spectrum: [Fs = ',num2str(Fs),' Hz]'));
set(gcf, 'NumberTitle', 'off');
% Plot single-sided amplitude spectrum.
if (semilog_scale)
semilogx(f,20*log10(2*abs(Y(1:NFFT/2+1))), color, 'LineWidth', 2);
else
plot(f,20*log10(2*abs(Y(1:NFFT/2+1))), color,'LineWidth', 2);
end;
title(title_string);
xlabel('Frequency (Hz)');
ylabel('|Y(f)| dB');
grid on;
% UPIITA IPN 2010
% Valencia Pesqueira José David
% Function used to obtain the synchronization factor for each
% branch in the DWT chain-processing program
function [x] = getsincdwt(n_etapas, rama, Lfiltrobase)
switch(n_etapas)
case 1 %One stage, two-branches. DWPT equivalent
x = 0;
case 2 %2 stages, 3 branches
switch(rama)
case 1 % High-pass branch
x = (Lfiltrobase-1)*2;
otherwise
x = 0;
end
case 3 %3 branches, 4 stages
switch(rama)
case 1 % High-pass branch
x = (Lfiltrobase-1)*2;
case 2
x = 10;
otherwise
x = 0;
end
end
% Experimental ANALISIS
% 2 etapas
% lfiltro - sinc_factor experimental
%
% 4 - 6 (4-1)*2 = 6
% 6 - 10 (6-1)*2 = 10
% 8 - 14 (8-1)*2 = 7
% ----------------------------------------------------
% Title: Discrete Wavelet Transform
% Author: David Valencia
% UPIITA IPN 2010
%
% Posted in DSPrelated.com
% http://www.dsprelated.com/showcode/47.php
%
% Computes the Discrete Wavelet Transform of
% n levels (and its branches) from a n sample input.
% Base filters can be of any lenght.
%
% Generalized DWT filter bank computed via the
% chain processing method (linear convolution)
%
% Dependencies:
% formfilters.m - http://www.dsprelated.com/showcode/44.php
% formfiltersdwt.m - http://www.dsprelated.com/showcode/45.php
% upsample2.m - http://www.dsprelated.com/showcode/10.php
% recorreder.m - http://www.dsprelated.com/showcode/43.php
% getsincdwt.m - http://www.dsprelated.com/showcode/46.php
%
% Revisions:
% v1.0a Commented and translated in English
% ----------------------------------------------------
close all; clear all; clc;
% ######################################
disp('== CHAIN PROCESSING DWT ==')
% Filter parameters
typeofbasis = 'o';
typbior = 'bior2.2';
typor = 'db2';
if(typeofbasis == 'b')
[Rf,Df] = biorwavf(typbior);
[h0,h1,g0,g1] = biorfilt(Df,Rf);
elseif (typeofbasis == 'o')
[h0,h1,g0,g1] = wfilters(typor);
end;
% Input values, change as needed
N = 16;
x = (1:N);
L = length(h0);
figure(1);
subplot(2,1,1);
stem(x);
xlabel('Original signal');
% Filter bank parameters, change as needed
n_stages = 3; %Of the low-pass part
% Checked for the minimal case: DWT = DWPT n_stages = 1
n_branches = n_stages + 1; %Of the low-pass part
niter = 300; %Number of iterations
% Define input buffer dimensions
hx = formfilters(n_stages, 1, h0, h1);
lhx = length(hx);
% Input buffer vector
inputbuffer = zeros(lhx,1);
% Synthesis input buffer
sbuffer = zeros(n_branches,lhx);
% This vector will store the length of each branch filter
Lfiltros = zeros(n_branches, 1);
% This vector will store the decimate factor for each branch
dec_factors = zeros(n_branches, 1);
% This vector will store the synchronization factor for each branch
sinc_factors = zeros(n_branches, 1);
% Cycle to get the synchronization factors
for j = 0:n_branches-1
try
sinc_factors(j+1) = getsincdwt(n_stages, j+1, L);
catch error
disp('ERROR: Error, experimentation is needed for this case');
disp('The results may not be correct');
% return;
end
end
%% Filter matrices formation
% This matrix will store each of the branch filters as vectors
H = zeros(n_branches, lhx); %Malloc
G = zeros(n_branches, lhx); %Malloc
for i = 0:n_stages
if i >= n_stages-1
dec_factors(i+1) = 2^n_stages;
else
dec_factors(i+1) = 2^(i+1);
end
hx = fliplr(formfiltersdwt(n_stages,n_stages+1-i,h0,h1));
gx = fliplr(formfiltersdwt(n_stages,n_stages+1-i,g0,g1));
lhx = length(hx);
lgx = length(gx);
Lfiltros(i+1) = lhx;
H(i+1,1:lhx) = hx;
G(i+1,1:lhx) = gx;
end
% Debug code
disp('Dimensiones de los filtros')
Lfiltros
disp('Factores de diezmado')
dec_factors
disp('Matriz de filtros análisis: ');
H
disp('Matriz de filtros síntesis: ');
G
chanbufftestigo = zeros(n_branches,1);
outputbuffer = zeros(1,niter);
%% MAIN CYCLE
for i = 1:niter %General FOR (for iterations)
i % Print iteration number
% Shifting of input buffer (sequentially)
inputbuffer = recorreder(inputbuffer,1);
if i<=N
inputbuffer(1)=x(i);
else
inputbuffer(1)=0;
end
inputbuffer %Print buffer (debug)
%% Analyisis stage (h0 and h1)
% The following cycle will select each of the branches for processing
% If the iteration counter is a multiply of the decimation factor,
% the convolution is calculated, otherwise, zeros are sent to the
% channel
y = zeros(n_branches,1); %Clear the output buffer
for j = 0:n_branches-1
fprintf('\nBranch: %d, Decimating factor: %d\n',j+1,dec_factors(j+1));
fprintf('\nFilter length: %d\n',Lfiltros(j+1));
if mod(i,dec_factors(j+1)) == 1
fprintf('i = %d is a multiply of the factor: %d\n',i,dec_factors(j+1));
tempfilt = H(j+1,1:Lfiltros(j+1));
% If the current iteration (clock cycle) is a multiply of the
% factor, the convolution is computed
for k=1:Lfiltros(j+1) %convolution
y(j+1,1) = y(j+1,1) + inputbuffer(k)*tempfilt(k);
end;
end
disp('Results in the channel');
chanbuff(:,1) = y %Debug printing
end
%% Synthesis stage (g0 and g1)
% Shifting and interpolation of the synthesis buffer
for j = 1:n_branches
sbuffer(j,:) = recorreder(sbuffer(j,:),1);
% Interpolation of the synthesis stage inputs
if mod(i,dec_factors(j)) == 1
fprintf('Inserting sample to the synthesis branch %d with dec_factor %d\n',j,dec_factors(j));
sbuffer(j,1) = chanbuff(j,1);
else
fprintf('Inserting a zero to the synthesis branch %d with dec_factor %d\n',j,dec_factors(j));
sbuffer(j,1) = 0;
end
end
disp('Synthesis buffer matrix');
sbuffer
xnbuff = zeros(n_branches,1);
for j=0:n_branches-1
fprintf('Branch: %d , dec_factor = %d',j+1,dec_factors(j+1));
% === BRANCH SYNCHRONIZATION ===
% The branches (except the two last ones down the bank filter)
% will only take a part of the vector that corresponds with their
% channel, taking 'Lx' elements, being Lx the number of coefficient
% that their filter has. An offset is applied
if j < n_branches - 2
[m,n] = size(sbuffer);
tempsinth = sbuffer(j+1,n-Lfiltros(j+1)+1:n) %TESTING
else % The lowest branches take the whole vector
tempsinth = sbuffer(j+1,1+sinc_factors(j+1):Lfiltros(j+1)+sinc_factors(j+1))
end
for k = 1 : Lfiltros(j+1) %Convolution
xnbuff(j+1,1) = xnbuff(j+1,1) + tempsinth(k)*G(j+1,k);
end
end
xnbuff
outputbuffer(i) = sum(xnbuff);
disp('Output buffer: ');
if i > N
disp(outputbuffer(1,i-N+1:i))
figure(1);
subplot(2,1,2);
stem(outputbuffer(1,i-N+1:i));
xlabel('Recovered signal');
else
disp(outputbuffer(1,1:N))
figure(1);
subplot(2,1,2);
stem(outputbuffer(1,1:N));
xlabel('Recovered signal');
end
pause;
end
% END OF PROGRAM >>>
%==============================================================================
%
% Gray Code Generator for Verilog
%
% This script generates a Verilog header (.vh) file which contains a set of
% of `define directives to establish Gray-coded states for a state machine.
% The output of this script is intended to be used in conjunction with a
% Verilog design which uses Gray coding in some application. For more
% information on Gray coding, please see
% http://mathworld.wolfram.com/GrayCode.html.
%
% Usage:
%
% The bit width of the Gray coded states is set as a script variable.
% 2^bit_width states are generated. The output filename is also
% set as a script variable.
%
% Author: Tom Chatt
%
%------------------------------------------------------------------------------
% Revision History:
%
% Original Version Tom Chatt 11/2/2010
%
%==============================================================================
clear all; clc;
%------------------------------------------------------------------------------
bit_width = 8; % Bit width of the generated code
% Print the generated code entries to a Verilog defines file?
print_to_v_def_file = true;
output_file = ['gray_code_',num2str(bit_width),'.vh']; % Output file name
% Gray code state name prefix. State names will be of the form
% GC<bit_width>B_<state number>.
prefix = ['GC',num2str(bit_width),'B_'];
%--------------Do not edit code below this point-------------------------------
% Generate the code, starting with 1 bit code and looping upward
code = [0; 1];
if bit_width ~= 1
for i = 2 : bit_width
code = [zeros(size(code,1), 1), code; ones(size(code,1), 1), flipud(code)]; %#ok<AGROW>
end
end
% Print out the generated code
fid = fopen(output_file, 'w');
for i = 1 : size(code,1)
macro_name = [prefix, num2str(i)];
macro_val = [num2str(bit_width),'''', dec2bin(binvec2dec(code(i,:)),bit_width)];
fprintf(fid, ['ifndef ',macro_name,'\n']);
fprintf(fid, [' ','`define ', macro_name, ' ', macro_val, '\n']);
fprintf(fid, 'endif\n');
end
fclose('all');
function op = vsola(ip, tsm_factor, P)
% Implementation of the variable parameter synchronised overlap add VSOLA algorithm
% This implementation makes use of the standard SOLA algorithm (Rocus and Wilgus, ICASSP 1986) and some efficient paramter settings for the SOLA algorithm (Dorran, Lawlor and Coyle, ICASSP 2003) and (Dorran, Lawlor and Coyle, DAFX 2003)
% Given an input, ip, the longest likely pitch period, P, and and a time scale modification factor, tsm_factor, return an output, op, that is a time scaled version of the input. The synthesis_overlap_size is the length, in samples of the lowest likely fundametal period of the input.
% for speech synthesis_overlap_size is set to (16/1000)*fs samples and for music synthesis_overlap_size is typically set to (20/1000)*fs samples
%
% As with all time-domain algorithms this will only work well for signals which have a strong periodic element. For more complex audio you should use a frequency-domain implementation like the phase vocoder
%
% David Dorran, Audio Research Group, Dublin Institute of Technology
% david.dorran@dit.ie
% http://eleceng.dit.ie/dorran
% http://eleceng.dit.ie/arg
%
% make sure input is mono and transpose if necessary
[r, c] = size(ip);
if r > 1
ip = ip';
end;
[r, c] = size(ip);
if r > 1
disp('Note :only works on mono signals');
op = [];
return
end;
% initialize the values of analysis_frame_length, analysis_window_offset, synthesis_frame_offset and length_of_overlap
desired_tsm_len = round(length(ip)*tsm_factor);
P = round(P); %longest likely pitch period in samples
Lmax = round(P * 1.5);% found this to a reasonable value for the Lmax- Lmax is the duration over which the correlation function is applied
stationary_length = (P * 1.5); % found this to a reasonable value for the stationary length - This is the max duration that could be discarded/repeated
analysis_window_offset = round((stationary_length - P)/abs(tsm_factor - 1)); % this equation was derived.
synthesis_window_offset = round(analysis_window_offset * tsm_factor);
analysis_frame_length = round(Lmax + synthesis_window_offset);
number_of_analysis_frames = floor((length(ip)- analysis_frame_length)/analysis_window_offset);
if number_of_analysis_frames < 2 %not much time-scaling being done just return the input
op = ip;
return;
end;
%the next two lines just ensure that the last frame finishes at the very end of the signal (not essential)
zpad = zeros(1, (number_of_analysis_frames*analysis_window_offset) + analysis_frame_length - length(ip));
ip = [ip zpad];
%initialize the output
op = zeros(1, desired_tsm_len);
%initialize the first output frame
op(1 : analysis_frame_length) = ip(1 : analysis_frame_length);
min_overlap = round(Lmax - P); %ensure that there is some minimum overlap
count = 0;
% Loop for the 2nd analysis frame to the number_of_analysis_frames
for m = 1 : number_of_analysis_frames
%grab the mth input frame
ip_frame = ip(analysis_window_offset * m : (analysis_window_offset * m) + analysis_frame_length - 1);
%grab the maximum overlapping segments from the inout frame and the current output
seg_1 = op(round(synthesis_window_offset*(m-1))+analysis_frame_length - Lmax : round(synthesis_window_offset*(m-1))+analysis_frame_length -1);
seg_2 = ip_frame(1: Lmax);
%compute the correlation of these segments
correlation = xcorr(seg_2, seg_1,'coeff');
%Find the best point to overlap (opt_overlap_length) making sure not to exceed the maximum or go below the minimum overlap.
correlation(length(correlation) - Lmax -1: length(correlation)) = -100;
correlation(1: min_overlap) = -100;
[max_correlation, opt_overlap_length] = max(correlation);
if(max_correlation == 0)
opt_overlap_length = Lmax;
end;
% offset = Lmax - opt_overlap_length;
% if ((offset + analysis_window_offset - synthesis_window_offset) >= 0 & (offset + analysis_window_offset - synthesis_window_offset) <= P)
% count = count +1;
% end;
% append mth analysis frame to the current synthesised output using a linear cross fade
ov_seg = linear_cross_fade(seg_1, ip_frame, opt_overlap_length);
ov_len =(round(synthesis_window_offset*m)+analysis_frame_length) - (round(synthesis_window_offset*(m-1))+analysis_frame_length - Lmax) + 1;
ov_seg = ov_seg(1:ov_len);
op(round(synthesis_window_offset*(m-1))+analysis_frame_length - Lmax: round(synthesis_window_offset*m)+analysis_frame_length) = ov_seg;
end; % end of for loop
% linear cross fade the first segment with the second segment given a certain amount of overlap
% |----------seg1----------|
% |---------------seg2-----------------------|
% |--overlap-|
function op = linear_cross_fade(seg_1, seg_2, overlap_length, cross_fade_duration)
error(nargchk(3,4,nargin));
if nargin < 4
cross_fade_duration = overlap_length;
end
if cross_fade_duration > overlap_length
cross_fade_duration = overlap_length;
end
% overlap the end of seg_1 with the start of seg_2 using a linear cross-fade
if (length(seg_1) < overlap_length),
seg_2 = seg_2(overlap_length - length(seg_1) + 1: length(seg_2));
overlap_length = length(seg_1);
end; % end of if statement
if (length(seg_2) < overlap_length),
seg_1 = seg_1(length(seg_1) - (overlap_length - overlap_length): length(seg_1));
overlap_length = length(seg_2);
end; % end of if statement
overlapping_region = zeros(1, cross_fade_duration); % initialize the overlapping region
seg_1 = seg_1(1: length(seg_1) - (overlap_length - cross_fade_duration));
op = zeros(1, length(seg_1) + length(seg_2) - cross_fade_duration);
if(overlap_length ~= 1)
linear_ramp1 = (cross_fade_duration-1:-1:0) ./(cross_fade_duration-1);
linear_ramp2 = (0:1:cross_fade_duration-1) ./(cross_fade_duration-1);
overlapping_region = (seg_1(length(seg_1)-cross_fade_duration+1:length(seg_1)).*linear_ramp1) + (seg_2(1: cross_fade_duration).*linear_ramp2);
end;
op = [seg_1(1:length(seg_1)-cross_fade_duration) ,overlapping_region , seg_2(cross_fade_duration+1:length(seg_2))];
% END of linear_cross_fade function
function [D] = dft_mtx(n)
f = 2*%pi/n; // Angular increment.
w = (0:f:2*%pi-f/2).' *%i; //Column.
//disp(w)
x = 0:n-1; // Row.
D = exp(-w*x); // Exponent of outer product.
for i = 1:n
for j = 1:n
if((abs(real(D(i,j)))<0.0001)&(abs(imag(D(i,j)))<0.0001))
D(i,j)=0;
elseif(abs(real(D(i,j)))<0.0001)
D(i,j)= 0+%i*imag(D(i,j));
elseif(abs(imag(D(i,j)))<0.0001)
D(i,j)= real(D(i,j))+0;
end
end
end
endfunction
#include <stdio.h>
#include <fcntl.h>
#include <sys/soundcard.h>
#define BUF_SIZE 2
/*buffers for sound device*/
unsigned char devbuf[BUF_SIZE];
/*File descriptor for device*/
int audio_fd;
/*The sound card is known as the DSP*/
char DEVICE_NAME[]="/dev/dsp";
/*Device Settings*/
int format;
int channels;
int fs;
int len;
int frag;
int devcaps;
int main()
{
unsigned int temp;
unsigned int yout;
/*Samples format is 16 bit unsigned*/
format = AFMT_U16_LE;
/*1 Channel, MONO*/
channels = 1;
/*Sampling Rate is 16 KHz*/
fs = 16000;
/*This is a parameter used to set the DSP for low latencies*/
frag = 0x00020004;
/******************************************************
Set parameters in sound card device
*****************************************************/
/*Open sound card device*/
if ((audio_fd = open(DEVICE_NAME,O_RDWR, 0)) == -1) {
/* Open of device failed */
perror(DEVICE_NAME);
exit(1);
}
if (ioctl (audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag) == -1)
{
perror ("SNDCTL_DSP_SETFRAGMENT");
exit (-1);
}
/*Set audio format*/
if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format) == -1) {
/* fatal error */
perror("SNDCTL_DSP_SETFMT");
exit(1);
}
/*Set number of channels*/
if (ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &channels) == -1) {
/* Fatal error */
perror("SNDCTL_DSP_CHANNELS");
exit(1);
}
/*Set sampling rate*/
if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &fs)==-1) {
/* Fatal error */
perror("SNDCTL_DSP_SPEED");
exit(1);
}
if (ioctl(audio_fd, SNDCTL_DSP_SYNC) == -1) {
/* fatal error */
perror("SNDCTL_DSP_SYNC");
exit(1);
}
/******************************************************
This is the infinite loop to:
1. Read a sample
2. Process the sample
3. Write the sample to soundcard output
*****************************************************/
while(1) {
/* This is a blocking read function, the application will wait
until the sound card captures a sample
*/
if ((len = read(audio_fd,devbuf, sizeof(devbuf))) == -1) {
perror("audio read");
exit(1);
}
/* We can pass this variable to a temporary value,
in this case as unsigned 16 value, and then use this value
for processing
*/
temp = (devbuf[0])|(devbuf[1]<<8);
/* In this case no processing is done so the value is passed to the output. You can also use this sample to build an audio file, or send it trought a communications interface, etc.
*/
yout = temp;
devbuf[0] = yout&0xFF;
devbuf[1] = (yout>>8)&0xFF;
/* This is the way the output samples are sent to the soundcard
*/
if ((len = write(audio_fd,devbuf,sizeof(devbuf)) == -1)) {
perror("audio write");
exit(1);
}
}
return 0;
}
%For a real-valued, single tone sine or cosine wave, estimate the frequency
%using an fft. Resolution will be limited by the sampling rate of the tone
%and the number of points in the fft.
%Procedure:
%1. Generate the test tone with a given Fs and N
%2. Take the fft and keep the first half
%3. Detect the maximum peak and its index
%4. Equate this index to a frequency
%Error Estimate:
% (Fs/N)= Hz/bin
%Things to keep in mind:
%Adding noise to the input will skew the results
%windowing will help with the fft
%% Clear and close everything
clc;
close all;
clear all; %remove this line if you are trying to use breakpoints
%% Just copy into m file, save and run
Fs = 1e6; %1MHz
fi = 1.333e3; %1kHz
t = 0:1/Fs:.5;
y = sin(2*pi*fi*t);
%Plot the time and frequency domain. Be sure to zoom in to see the waveform
%and spectrum
figure;
subplot(2,1,1);
temp = (2/fi)*Fs;
plot(y);
xlabel('time (s)');
subplot(2,1,2);
sX=fft(y);
N=length(sX);
sXM = abs(sX(1:floor(end/2))).^2; %take the magnitude and only keep 0:Fs/2
plot(0:Fs/N:(Fs/2)-1,sXM);
xlabel('Frequency')
ylabel('Magnitude')
[vv, ii]=max(sXM); %find the index of the largest value in the spectrum
freqEst = (ii-1)*Fs/N; %units are Hz
resMin = Fs/N; %units are Hz
display(freqEst);%display to the command window the results
display(resMin);
function [hx] = formafiltrosdwpt(n_stages,branch,h0,h1)
p = branch;
% Integrated version for DWPT/TMX filter generation
hx = 0;
hx(1) = 1;
switch n_stages
case 1
if mod(branch,2) ~= 0
hx = h0;
else
hx = h1;
end
case 2
switch branch
case 1
hx = conv(h0,upsample(h0,2));
case 2
hx = conv(h0,upsample(h1,2));
case 3
hx = conv(h1,upsample(h0,2));
case 4
hx = conv(h1,upsample(h1,2));
otherwise
beep;
fprintf('\nERROR');
end
otherwise
for i=0:n_stages-2
q = floor(p /(2^(n_stages-1-i)));
if (q == 1)
hx = conv(hx,upsample(h1,2^i));
else
hx = conv(hx,upsample(h0,2^i));
end
p = mod(p,2^(n_stages-1-i)); %For DWPT and TMX
end
t = mod(branch,2);
if(t == 1)
hx = conv(hx,upsample(h0,2^(n_stages-1)));
else
hx = conv(hx,upsample(h1,2^(n_stages-1)));
end
end
% UPIITA IPN 2010
% José David Valencia Pesqueira
% This program is useful to convert numbers in MATLAB's Double
% format to a text file in float format for C compilers
% You should copy the resulting text to a file and save it with .h
% extension
% THIS PROGRAM RECEIVES AN UNIDIMENTIONAL VECTOR OF DOUBLE NUMBERS
% close all; clear all; clc;
function double2cfloat(x , namex, y, namey, sinc_factor)
[m,n] = size(x);
fprintf('// Begin of file\n\n');
fprintf('#define sinc %d // Sincronization factor\n',sinc_factor);
fprintf('#define N %d // Filter length\n',n);
if m~=0
fprintf('#define M %d // Number of filters(branches)\n\n',m);
fprintf('float %s[M][N]=',namex);
else
fprintf('float %s[N]=',namex);
end
disp('');
disp('{');
for i=0:m-1 %Rows
if m~=1
disp('{');
end
for j=0:n-1 %columns
fprintf('%1.4e,\n',x(i+1,j+1));
end
if m~=1
fprintf('},\n');
end
end
disp('};');
fprintf('\n\n');
if m~=0
fprintf('float %s[M][N]=',namey);
else
fprintf('float %s[N]=',namey);
end
disp('');
disp('{');
for i=0:m-1 %Rows
if m~=1
disp('{');
end
for j=0:n-1 %columns
fprintf('%1.4e,\n',y(i+1,j+1));
end
if m~=1
fprintf('},\n');
end
end
disp('};');
fprintf('\n// EOF\n\n');
/* Interruption.c
JOSE DAVID VALENCIA PESQUEIRA
UPIITA-IPN
THIS PROGRAM DETECTS AN EXTERNAL INTERRUPTION ON A GPIO PIN*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <csl_gpio.h>
#include <csl_gpiohal.h>
#include <csl_irq.h>
/* GLOBAL VARIABLES
The flags are marked as volatile, to tell the compiler
that these can be modified by an external event, avoiding
to put them on registers and rather putting them on RAM
so they're ready for immediate use
*/
volatile int startflag = 0;
GPIO_Handle gpio_handle; /* Handle for the GPIO */
// GPIO Registers configuration
GPIO_Config gpio_config = {
0x00000000,
// gpgc = Interruption passtrhrough mode and direct GPIO control mode
0x0000FFFF, // gpen = All GPIO 0-15 pins enabled
0x00000000, // gdir = All GPIO pins as inputs
0x00000000, // gpval = Stores logical level of pins
0x00000010, // IRQ enable for pin 4
0x00000010, // Enable Event for pin 4
0x00000000 // gppol -- default state
};
irq_ext_enable(){
/* First, globally disable interruptions
in the CSR (Control Status Register).
Bit 0 is the GIE (Global Interrupt Enable)*/
CSR = (CSR)&(0xFFFFFFFE);
// Enable NMIE bit in the IER (bit 1)
IER |= 0x00000002;
// Enable INT4 bit in the IER (4th bit)
IER |= 0x00000010;
// Finally, globally enable interruptions in the CSR
CSR |= 0x00000001;
}
main()
{
// To configure the GPIO
gpio_handle = GPIO_open( GPIO_DEV0, GPIO_OPEN_RESET );
GPIO_config(gpio_handle,&gpio_config);
irq_ext_enable();
comm_intr(); //init DSK
DSK6713_LED_init();
while(startflag == 0);
printf(“La interrupción externa encendió el led 3 del dsk6713\n”);
while(1) // Infinite While
}
interrupt void c_int04() //ISR
{
startflag = 1;
iter = 0;
DSK6713_LED_on(0); //To turn on the led
}