function Demo
close all
T = 1; %Sampling period.
B = 0.7; %Two-sided bandwidth.
%Plot error spectrum for P = 10, 20, and 30.
PlotErrorSpectrum(T,B,10);
figure
PlotErrorSpectrum(T,B,20);
figure
PlotErrorSpectrum(T,B,30);
function PlotErrorSpectrum(T,B,P)
% Frequency grid specification in figure.
f0 = 0;
M = (2*P+1)*10;
Df = B/(2*M);
f = f0+Df*(0:M-1);
ESinc = zeros(size(f));
Eg = zeros(size(f));
%Look for the maximum error among different shifts u for each frequency in f.
for u = -0.5:1/((2*P+1)*5):0.5
HRef = exp(1i*2*pi*f*u); %Ideal spectrum.
HSinc = chirpzDFT(sinc((-P:P)+u/T),-P*T,T,f0,Df,M); %Sinc spectrum.
Hg = chirpzDFT(gPulseCoefs(u,T,B,P),-P*T,T,f0,Df,M); %g-pulse spectrum.
ESinc = max([ESinc;abs(HRef-HSinc)]); %Compute current max. error for sinc.
Eg = max([Eg;abs(HRef-Hg)]); %Compute current max. error for g.
end
plot(f,20*log10([ESinc;Eg].'))
xlabel('Freq. (f*T)')
ylabel('Maximum error (dB)')
legend('sinc pulse','g pulse','Location','NorthOutside')
pr = get(gca,'YTick');
text(0,2*pr(end)-pr(end-1),['B*T = ',num2str(B*T),', P = ',num2str(P)])
title('Error spectrum (maximum for all possible shifts u)')
grid on
function c = gPulseCoefs(u,T,B,P)
t = (-P:P)*T+u;
c = sinc(t/T).*real(sinc((1-B*T)*sqrt((t/T).^2-P^2)))/real(sinc(1i*(1-B*T)*P));
function X = chirpzDFT(x,to,Dt,fo,Df,M)
%Author: J. Selva.
%Date: November 2011.
%
%This function computes the DFT for two regular time and frequency grids with arbitrary
%starting points and spacings, using the Chirp-z Transform. Specifically, it computes
%
% N
% X(k) = sum x(n)*exp(-j*2*pi*(fo+Df*(k-1))*(to+Dt*(n-1))), 1 <= k <= M.
% n=1
%
%Input parameters:
%
% x: Signal samples.
% to: Instant of first sample in x.
% Dt: Time spacing between consecutive samples of x.
% fo: First frequency in which the Fourier sum is computed.
% Df: Spacing of the desired frequency grid.
% M: Desired number of output samples.
%
%The algorithm is explained in Sec. 9.6.2, page 656 of
%
% A.V. Oppenheim, R. W. Schafer, J. R. Buck, "Discrete-time signal processing," second
% edition, 1998.
%
x = x(:).';
N = numel(x);
P = 2^ceil(log2(M+N-1));
%The next three lines do not depend on the vector x, and so they can be pre-computed if
%the time and frequency grids do not change, (i.e, for computing the transform of
%additional vectors). Thus, this algorithm just involves two FFTs for fixed grids and
%three if the grids change.
a = exp(-1i*2*pi*((1:N)*Dt*(fo-Df)+Dt*Df*(1:N).^2/2));
b = exp(-1i*2*pi*((to-Dt)*(fo+(0:M-1)*Df)+Dt*Df*(1:M).^2/2));
phi = fft(exp(1i*2*pi*Dt*Df*(1-N:M-1).^2/2),P); %FFT of chirp pulse.
%Weigh x using a and perform FFT convolution with phi.
X = ifft( fft(x.*a,P) .* phi );
%Truncate the convolution tails and weigh using b.
X = X(N:M+N-1) .* b;
function xdft=fdft(x)
N=length(x);
xdft(1,N)=0; % defining a 1xN sequence with all the elements equals to zero.
%*************THIS IS THE DFT IMPLEMENTATION**************
%For each value of k, the Summatory function is computed over the interval 0<n<N-1.
for k=0:N-1,
for n=0:N-1,
xdft(k+1)=xdft(k+1) + x(n+1)*exp(-j*2*pi*k*n/N);
end
end
%NOTE: You may skip the use of for-loops by defining k and n as two N-points sequences. This is:
% k=0:N-1; n=0:N-1;
%The DFT is now computed in matrix form (as a matrix multiplication of the N-points Fourier Matrix and the discrete-time sequence x).
/* -------------- SinCos.h begins -------------- */
#ifndef __SINCOS_H__
#define __SINCOS_H__
#include "types.h"
/*---------------------------------------------------------------------------;
; This function computes the sine of an angle using the Maclaurin series ;
; expansion method. Input angle is signed fractional where -1 corresponds to ;
; -pi and +1 to +pi; output is signed fractional and the minimum negative ;
; value is limited to -1+2^(-15) (0x8001 hexadeximal) to avoid overflow in ;
; subsequent calculations. ;
; ;
; Input: Y0 = angle (signed fractional; -1 = -pi, +1 = +pi) ;
; ;
; Output: Y0 = sine (signed fractional) ;
; ;
; Registers modified: A, B, X0, Y ;
;---------------------------------------------------------------------------*/
asm Frac16 Sin(Frac16 angle);
/*---------------------------------------------------------------------------;
; This function computes the cosine of an angle using the Maclaurin series ;
; expansion method. Input angle is signed fractional where -1 corresponds to ;
; -pi and +1 to +pi; output is signed fractional and the minimum negative ;
; value is limited to -1+2^(-15) (0x8001 hexadeximal) to avoid overflow in ;
; subsequent calculations. ;
; ;
; Input: Y0 = angle (signed fractional; -1 = -pi, +1 = +pi) ;
; ;
; Output: Y0 = cosine (signed fractional) ;
; ;
; Registers modified: A, B, X0, Y ;
;---------------------------------------------------------------------------*/
asm Frac16 Cos(Frac16 angle);
#endif //ifndef __SINCOS_H__
/* -------------- SinCos.h ends -------------- */
/* -------------- SinCos.c begins -------------- */
/*---------------------------------------------------------------------------;
; This function computes the sine of an angle using the Maclaurin series ;
; expansion method. Input angle is signed fractional where -1 corresponds to ;
; -pi and +1 to +pi; output is signed fractional and the minimum negative ;
; value is limited to -1+2^(-15) (0x8001 hexadeximal) to avoid overflow in ;
; subsequent calculations. ;
; ;
; Input: Y0 = angle (signed fractional; -1 = -pi, +1 = +pi) ;
; ;
; Output: Y0 = sine (signed fractional) ;
; ;
; Registers modified: A, B, X0, Y ;
;---------------------------------------------------------------------------*/
asm Frac16 Sin(Frac16 angle){
CLR.W Y1 //Clear Y1
MOVE.W Y0,B //Compute absolute value of angle
ABS B
CMP.W #$4000,B //|angle| > pi/2?
BLT SinAngleOK //No, proceed
ADD.W #$8000,Y0 //Yes, add pi and set flag for
BFSET #$0001,Y1 //final negation of result
SinAngleOK: MPYR Y0,Y0,A //Compute angle squared
MOVE.W A,X0 //X0 = angle squared
MOVE.W #$0002,B //Compute Maclaurin expansion
MOVE.W #$FFE2,A
MACR X0,B1,A //A1 = first partial result
MOVE.W #$0150,B
MACR X0,A1,B //B1 = second partial result
MOVE.W #$F669,A
MACR X0,B1,A //A1 = third partial result
MOVE.W #$28CD,B
MACR X0,A1,B //B1 = fourth partial result
MOVE.W #$AD52,A
MACR X0,B1,A //A1 = fifth partial result
MOVE.W #$3244,B
MACR X0,A1,B //B1 = sixth partial result
MOVE.W #$0003,X0 //Required shift amount
MPYR B1,Y0,A //A = result / 8
CMP #$1000,A //If magnitude is maximum
BNE SinCheckSatL //saturate the result
MOVE.W #$7FFF,A
BRA SinValOK
SinCheckSatL: CMP.W #$F000,A
BNE SinNoSat
MOVE.W #$8001,A
BRA SinValOK
SinNoSat: ASLL.L X0,A //Shift to get correct result
//(Maclaurin coefficients are
//divided by 8 to avoid overflow)
SinValOK: BRCLR #$0001,Y1,Update_Sin //Negate result if |angle| was
NEG A //greater than pi/2
Update_Sin: MOVE.W A,Y0 //Save result
RTS //Return from subroutine
}
/*---------------------------------------------------------------------------;
; This function computes the cosine of an angle using the Maclaurin series ;
; expansion method. Input angle is signed fractional where -1 corresponds to ;
; -pi and +1 to +pi; output is signed fractional and the minimum negative ;
; value is limited to -1+2^(-15) (0x8001 hexadeximal) to avoid overflow in ;
; subsequent calculations. ;
; ;
; Input: Y0 = angle (signed fractional; -1 = -pi, +1 = +pi) ;
; ;
; Output: Y0 = cosine (signed fractional) ;
; ;
; Registers modified: A, B, X0, Y ;
;---------------------------------------------------------------------------*/
asm Frac16 Cos(Frac16 angle){
ADD.W #$4000,Y0 //Add pi/2 to angle
JSR Sin //Call sine function
RTS //Return from subroutine
}
/* -------------- SinCos.c ends -------------- */
/* -------------- Usage example begins ------------- */
/* application specific includes */
#include "SinCos.h"
/* global variables */
Frac16 Angle,cosphi,sinphi;
/* Function calls */
cosphi=Cos(Angle); //Compute sin and cos of angle
sinphi=Sin(Angle); //(for use in Park transforms)
/* -------------- Usage example ends ------------- */
function [p]= RaisedCosineSpectrum()
//Practical Solution for Intersymbol Interference
//Raised Cosine Spectrum
rb = input('Enter the bit rate:');
Tb =1/rb;
t =-3:1/100:3;
Bo = rb/2;
Alpha =0; //roll-off factor Intialized to zero
x =t/Tb;
for j =1:3
for i =1:length(t)
if((j==3)&((t(i)==0.5)|(t(i)==-0.5)))
p(j,i) = sinc_new(2*Bo*t(i));
else
num = sinc_new(2*Bo*t(i))*cos(2*%pi*Alpha*Bo*t(i));
den = 1-16*(Alpha^2)*(Bo^2)*(t(i)^2)+0.01;
p(j,i)= num/den;
end
end
Alpha = Alpha+0.5;
end
a =gca();
plot2d(t,p(1,:))
plot2d(t,p(2,:))
poly1= a.children(1).children(1);
poly1.foreground=2;
plot2d(t,p(3,:))
poly2= a.children(1).children(1);
po1y2.foreground=4;
poly2.line_style = 3;
xlabel('t/Tb------>');
ylabel('p(t)------->');
title('RAISED COSINE SPECTRUM - Practical Solution for ISI')
legend(['ROlloff Factor =0','ROlloff Factor =0.5','ROlloff Factor =1'])
xgrid(1)
endfunction
//Result
//Enter the bit rate:1
function[y,M] = adapt_filt(xlms,B,h,delta,l,l1)
//x = the signal from the speaker directly
//B = the signal thorugh the echo path
//h = impulse response of adaptive filter
//l = length of signal 'x'
//l1 = length of adaptive filter order
for k = 1:150
for n = 1:l
xcap = xlms((n+l1-1):-1:(n+l1-1)-l1+1);
yout(n) = h*xcap;
e(n) = B(n)- yout(n);
xnorm = 0.001+(xcap*xcap');
h = h+((delta*e(n))*(xcap'));
end
eold = 0.0;
for i = 1:l
MSE = eold+(e(i)^2);
eold = MSE;
end
if MSE <= 0.0001 then
break;
end
end
y = zeros(1,length(e));
M = zeros(1,length(h));
y = e;
M = h;
endfunction
function out = create_pink_noise(Fs, Sec, Amp)
% Creates a pink noise signal and saves it as a wav file
%
% Usage: create_noise(Fs, Sec, Amp);
%
% Fs is the desired sampling rate
% Sec is the duration of the signal in seconds
% Amp is the amplitude in dB of the signal (0dB to -144dB)
%
% Author: sparafucile17 06/14/02
%error trapping
if((Amp > 0) || (Amp < -144))
error('Amplitude is not within the range of 0dB to -144dB');
end
%Create Whitenoise
white_noise = randn((Fs*Sec)+1,1);
%Apply weighted sum of first order filters to approximate a -10dB/decade
%filter. This is Paul Kellet's "refined" method (a.k.a instrumentation
%grade) It is accurate to within +/-0.05dB above 9.2Hz
b=zeros(7,1);
for i=1:((Fs*Sec)+1)
b(1) = 0.99886 * b(1) + white_noise(i) * 0.0555179;
b(2) = 0.99332 * b(2) + white_noise(i) * 0.0750759;
b(3) = 0.96900 * b(3) + white_noise(i) * 0.1538520;
b(4) = 0.86650 * b(4) + white_noise(i) * 0.3104856;
b(5) = 0.55000 * b(5) + white_noise(i) * 0.5329522;
b(6) = -0.7616 * b(6) - white_noise(i) * 0.0168980;
pink_noise(i) = b(1) + b(2) + b(3) + b(4) + b(5) + b(6) + b(7) + white_noise(i) * 0.5362;
b(7) = white_noise(i) * 0.115926;
end
%Normalize to +/- 1
if(abs(min(pink_noise)) > max(pink_noise))
pink_noise = pink_noise / abs(min(pink_noise));
else
pink_noise = pink_noise / max(pink_noise);
end
%Normalize to prevent positive saturation (We can't represent +1.0)
pink_noise = pink_noise /abs(((2^31)-1)/(2^31));
%Scale signal to match desired level
pink_noise = pink_noise * 10^(Amp/20);
%Output noise signal
out = pink_noise(1:end-1);
function thr = oracleshrink1(CD,T)
%function used to calculate threshold for oracleshrink method
CD = CD(:)';
n = length(CD);
sx2 = (T-CD).^2;
b = cumsum(sx2);
[risk,best] = min(b);
hr = sqrt(sx2(best));
// Include the filter coefficients and corresponding variables
#include "IIRBSF.h"
// The intermediate values in the Direct Form II filter
float delay_w[MWSPT_NSEC][3]; // delay_w[i][j] <=> w_i(n-j), j=0,1,2
// i is the section, j the delay
float sectionOut; // yk[n] <=> sectionout
interrupt void isr() //Interrupt function t=125us, f = 8kHz
{
short i; // i loops through the MWSPT_NSEC number of sections
// Do the filtering if DIP switch 1 up
if (get_DIP1() == 1) {
// In the first section, read in the x-value, apply the first stage gain
sectionOut = NUM[0][0] * get_sample();
for (i=1; i<MWSPT_NSEC; i++) { // Loop through all the sections
// Get the new delay_w[0];
delay_w[i][0] = sectionOut - DEN[i][1]*delay_w[i][1] - DEN[i][2]*delay_w[i][2];
// Get the output of this section
sectionOut = NUM[i][0]*delay_w[i][0] + NUM[i][1]*delay_w[i][1] + NUM[i][2]*delay_w[i][2];
// Delay the w's for the next interrupt
delay_w[i][2] = delay_w[i][1];
delay_w[i][1] = delay_w[i][0];
}
// Apply the gain, convert to short and send out
send_output((short)(2 * sectionOut));
// Gain of 2 chosen heuristically for speech from PC
} else { // If DIP switch 1 down, == 0, then just pass through signal.
send_output(get_sample());
}
return; //interrupt done
}
void main()
{
short i,j;
for (i=0; i<MWSPT_NSEC; i++)
for (j=0; j<3; j++)
delay_w[i][j] = 0; // init intermediate array
init_all(); // init all
while(1); // infinite loop
}
//iirFilter.c
// Include the filter coefficients and corresponding variables
#include "IIRLPF.h"
#define A 1 //The amplitude of added wave
#define FREQ 1000 //The frequency of the sine wave in Hz
// The intermediate values in the Direct Form II filter
float delay_w[MWSPT_NSEC][3];
// delay_w[i][j] <=> w_i(n-j), j=0,1,2
// i is the section, j the delay
float sectionOut; // yk[n] <=> sectionout
interrupt void isr() //Interrupt function t=125us, f = 8kHz
{
short i; // i loops through the MWSPT_NSEC number of sections
int period = 8000 / FREQ;
float rad = FREQ * 2 * pi;
int j = 0;
// Do the filtering if DIP switch 1 up
if (get_DIP1() == 1) {
// In the first section, we read in the x-value, apply the first stage gain
sectionOut = NUM[0][0] * get_sample();
for (i=1; i<MWSPT_NSEC; i++) { // Loop through all the sections
// Get the new delay_w[0];
delay_w[i][0] = sectionOut - DEN[i][1]*delay_w[i][1] - DEN[i][2]*delay_w[i][2];
// Get the output of this section
sectionOut = NUM[i][0]*delay_w[i][0] + NUM[i][1]*delay_w[i][1] + NUM[i][2]*delay_w[i][2];
// Delay the w's for the next interrupt
delay_w[i][2] = delay_w[i][1];
delay_w[i][1] = delay_w[i][0];
}
//Add a tone to sectionOut
sectionOut = sectionOut + A*sin(rad*j); //Add a sine wave of freq rad to sectionOut
j = (j + 1) % period; //Increment the sine wave counter
// Apply the gain, convert to short and send out
send_output((short)(2 * sectionOut));
// Gain of 2 chosen heuristically for speech from PC
} else { // If DIP switch 1 down, == 0, then just pass through signal.
send_output(get_sample());
}
return; // return from interrupt
}
void main()
{
short i,j;
for (i=0; i<MWSPT_NSEC; i++)
for (j=0; j<3; j++)
delay_w[i][j] = 0; // init intermediate array
init_all(); // init all
while(1); // infinite loop
}
//iirFilterSwitch.c
// Include the filter coefficients and corresponding variables
#include "IIRLPF.h"
#include "IIRHPF.h"
// The intermediate values in the Direct Form II filter
float delay_w1[MWSPT_NSEC1][3];
float delay_w2[MWSPT_NSEC2][3];
// delay_w[i][j] <=> w_i(n-j), j=0,1,2
// i is the section, j the delay
float sectionOut; // yk[n] <=> sectionout
interrupt void isr() //Interrupt function
{
short i; // i loops through the MWSPT_NSEC number of sections
// Use the LPF if DIP switch 1 up
if (get_DIP1() == 1) {
// In the first section, we read in the x-value, apply the first stage gain
sectionOut = NUM1[0][0] * get_sample();
for (i=1; i<MWSPT_NSEC1; i++) { // Loop through all the sections
// Get the new delay_w1[0];
delay_w1[i][0] = sectionOut - DEN1[i][1]*delay_w1[i][1] - DEN1[i][2]*delay_w1[i][2];
// Get the output of this section
sectionOut = NUM1[i][0]*delay_w1[i][0] + NUM1[i][1]*delay_w1[i][1] + NUM1[i][2]*delay_w1[i][2];
// Delay the w's for the next interrupt
delay_w1[i][2] = delay_w1[i][1];
delay_w1[i][1] = delay_w1[i][0];
}
// Apply the gain, convert to short and send out
send_output((short)(2 * sectionOut));
// Gain of 2 chosen heuristically for speech from PC
} else { // If DIP switch 1 down, == 0, then use HPF
sectionOut = NUM2[0][0] * get_sample();
for (i=1; i<MWSPT_NSEC2; i++) { // Loop through all the sections
// Get the new delay_w2[0];
delay_w2[i][0] = sectionOut - DEN2[i][1]*delay_w2[i][1] - DEN2[i][2]*delay_w2[i][2];
// Get the output of this section
sectionOut = NUM2[i][0]*delay_w2[i][0] + NUM2[i][1]*delay_w2[i][1] + NUM2[i][2]*delay_w2[i][2];
// Delay the w's for the next interrupt
delay_w2[i][2] = delay_w2[i][1];
delay_w2[i][1] = delay_w2[i][0];
}
// Apply the gain, convert to short and send out
send_output((short)(2 * sectionOut));
// Gain of 2 chosen heuristically for speech from PC
}
return; // return from interrupt
}
void main()
{
short i,j;
for (i=0; i<MWSPT_NSEC1; i++)
for (j=0; j<3; j++)
delay_w1[i][j] = 0; // init intermediate array
for (i=0; i<MWSPT_NSEC2; i++)
for (j=0; j<3; j++)
delay_w2[i][j] = 0; // init intermediate array
init_all(); // init all
while(1); // infinite loop
}
// These coefficients are used to filter
#include "yourfiltercoeffs.h"
// scale factor, S_h = 2^K.
#define K 15
int filterout = 0; // In fixed-point implementation, the accumulator is 32-bit int
short delay[LENGTH]; // Short is the 16-bit integer variable
interrupt void isr() // Interrupt function
{
short i;
int Sx = 1;
// Do the filtering as per fixfilt if DIP switch 1 up
if (get_DIP1() == 1) {
// Direct-Form FIR
delay[0] = Sx * get_sample(); // input for filter
filterout = hMax[0] * delay[0]; // Set up filter sum
// Notice, C-arrays go from 0..LENGTH-1
for (i = LENGTH-1; i > 0; i--){ // Get sum of products
filterout += hMax[i] * delay[i];
delay[i] = delay[i-1]; // Renew input array
}
filterout = (filterout>>K); //Move into the lower 16 bits, reverses scaling
//Sign extension carries the upper bit down if negative
send_output(filterout); // output for filter
} else { // If DIP switch 1 down, == 0, then just pass through signal.
send_output(get_sample());
}
return; // return from interrupt
}
void main()
{
short i;
for (i=0; i<= LENGTH-1; i++) {
delay[i] = 0; // init filter processing array
}
init_all(); // init all
while(1); // infinite loop
}
#define COMB_FILTER_ORDER 3 // Filter Order, i.e., M
#define DELAY_ARRAY_SIZE 9 // Number of (delayed) input samples to store
int filtersum; // Sum-of-products accumulator for calculating the filter output value
int delay[DELAY_ARRAY_SIZE]; // Array for storing (delayed) input samples
static int gain1 = 1;
static int gain2 = 4;
interrupt void isr() //Interrupt service routine
{
short i; // Loop counter
delay[0] = get_sample() / gain1; // Read filter input sample from ADC and scale the sample
filtersum = delay[0]; // Initialize the accumulator
for (i = COMB_FILTER_ORDER; i > 0; i--)
{
filtersum += delay[i]; // Accumulate array elements
delay[i] = delay[i-1]; // Shift delay elements by one sample
}
filtersum *= gain2; // Scale the sum-of-products
send_output(filtersum); // write filter output sample to DAC
return; // interrupt servicing complete
}
void main()
{
short i; // loop counter
for (i=0; i< DELAY_ARRAY_SIZE; i++) // Initialize delay elements with 0
{
delay[i] = 0;
}
init_all(); // global initialization
while(1); // infinite loop
// do nothing except wait for the interrupt
}