Bank-switched Farrow resampler
% **************************************************************
% bank-switched Farrow resampler
% M. Nentwig, 2011
% Note: Uses cyclic signals (wraps around)
% **************************************************************
close all; clear all;
% inData contains input to the resampling process (instead of function arguments)
inData = struct();
% **************************************************************
% example coefficients.
% Each column [c0; c1; c2; ...] describes a polynomial for one tap coefficent in fractional time ft [0, 1]:
% tapCoeff = c0 + c1 * ft + c2 * ft ^ 2 + ...
% Each column corresponds to one tap.
% the matrix size may be changed arbitrarily.
%
% The example filter is based on a 6th order Chebyshev Laplace-domain prototype.
% **************************************************************
if false
% for comparison, this is a conventional design (no bank switching)
inData.cMatrix =[ -8.57738278e-3 7.82989032e-1 7.19303539e+000 6.90955718e+000 -2.62377450e+000 -6.85327127e-1 1.44681608e+000 -8.79147907e-1 7.82633997e-2 1.91318985e-1 -1.88573400e-1 6.91790782e-2 3.07723786e-3 -6.74800912e-3
2.32448021e-1 2.52624309e+000 7.67543936e+000 -8.83951796e+000 -5.49838636e+000 6.07298348e+000 -2.16053205e+000 -7.59142947e-1 1.41269409e+000 -8.17735712e-1 1.98119464e-1 9.15904145e-2 -9.18092030e-2 2.74136108e-2
-1.14183319e+000 6.86126458e+000 -6.86015957e+000 -6.35135894e+000 1.10745051e+001 -3.34847578e+000 -2.22405694e+000 3.14374725e+000 -1.68249886e+000 2.54083065e-1 3.22275037e-1 -3.04794927e-1 1.29393976e-1 -3.32026332e-2
1.67363115e+000 -2.93090391e+000 -1.13549165e+000 5.65274939e+000 -3.60291782e+000 -6.20715544e-1 2.06619782e+000 -1.42159644e+000 3.75075865e-1 1.88433333e-1 -2.64135123e-1 1.47117661e-1 -4.71871047e-2 1.24921920e-2] / 231.46 * 20;
inData.nBanks = 1;
else
% same example filter as above, but now the matrix contains three alternative coefficient banks for each tap.
% The order was reduced from cubic to quadratic.
% column 1: first bank, tap 1
% column 2: second bank, tap 1
% column 3: third bank, tap 1
% column 4: first bank, tap 2
% and so on
inData.cMatrix =[ 2.87810386e-4 4.70096244e-3 7.93412570e-2 4.39824536e-1 1.31192924e+000 2.67892232e+000 4.16465421e+000 5.16499621e+000 5.15592605e+000 3.99000369e+000 2.00785470e+000 -7.42377060e-2 -1.52569354e+000 -1.94402804e+000 -1.40915797e+000 -3.86484652e-1 5.44712939e-1 9.77559688e-1 8.32191447e-1 3.22691788e-1 -2.13133045e-1 -5.08501962e-1 -4.82928807e-1 -2.36313854e-1 4.76034568e-2 2.16891966e-1 2.20894063e-1 1.08361553e-1 -2.63421832e-2 -1.06276015e-1 -1.07491548e-1 -5.53793711e-2 4.86314061e-3 3.94357182e-2 4.06217506e-2 2.17199064e-2 1.60318761e-3 -8.40370106e-3 -8.10525279e-3 -3.62112499e-3 -4.13413072e-4 2.33101911e-4
-3.26760325e-3 -6.46028234e-3 1.46793247e-1 5.90235537e-1 1.18931309e+000 1.57853546e+000 1.40402774e+000 5.76506323e-1 -6.33522788e-1 -1.74564700e+000 -2.24153717e+000 -1.91309453e+000 -9.55568978e-1 1.58239169e-1 9.36193787e-1 1.10969783e+000 7.33284446e-1 1.06542194e-1 -4.15412084e-1 -6.06616434e-1 -4.54898908e-1 -1.20841199e-1 1.82941623e-1 3.12543429e-1 2.49935829e-1 8.05376898e-2 -7.83213666e-2 -1.47769751e-1 -1.18735248e-1 -3.70656555e-2 3.72608374e-2 6.71425397e-2 5.17812605e-2 1.55564930e-2 -1.40896327e-2 -2.35058137e-2 -1.59635057e-2 -3.44701792e-3 4.14108065e-3 4.56234829e-3 1.59503132e-3 -3.17301882e-4
5.64310141e-3 7.74786707e-2 2.11791763e-1 2.84703201e-1 1.85158633e-1 -8.41118142e-2 -3.98497442e-1 -5.86821615e-1 -5.40397941e-1 -2.47558080e-1 1.50864737e-1 4.59312895e-1 5.41539400e-1 3.84673917e-1 9.39576331e-2 -1.74932542e-1 -3.01635463e-1 -2.56239225e-1 -9.87146864e-2 6.82216764e-2 1.59795852e-1 1.48668245e-1 6.62563431e-2 -2.71234898e-2 -8.07045577e-2 -7.76841351e-2 -3.55333136e-2 1.23206602e-2 3.88535040e-2 3.64199073e-2 1.54608563e-2 -6.59814558e-3 -1.72735099e-2 -1.46307777e-2 -5.04363288e-3 3.31049461e-3 6.01267607e-3 3.83904192e-3 3.92549958e-4 -1.36315264e-3 -9.76017430e-4 7.46699178e-5] / 133.64 * 20;
inData.nBanks = 3;
end
% **************************************************************
% Create example signal
% **************************************************************
nIn = 50; % used for test signal generation only
if false
% complex signal
inData.signal = cos(2*pi*(0:(nIn-1)) / nIn) + cos(2*2*pi*(0:(nIn-1)) / nIn) + 1.5;
else
% impulse response
inData.signal = zeros(1, nIn); inData.signal(1) = 1; %
% inData.cMatrix = 0 * inData.cMatrix; inData.cMatrix(1, 1) = 1; % enable to show constant c in first tap, first bank
% inData.cMatrix = 0 * inData.cMatrix; inData.cMatrix(2, 1) = 1; % enable to show linear c in first tap, first bank
% inData.cMatrix = 0 * inData.cMatrix; inData.cMatrix(3, 1) = 1; % enable to show quadratic c in first tap, first bank
% inData.cMatrix = 0 * inData.cMatrix; inData.cMatrix(1, 2) = 1; % enable to show constant c in first tap, second bank
end
% **************************************************************
% Resample to the following number of output samples
% must be integer, otherwise arbitrary
% **************************************************************
inData.nSamplesOut = floor(nIn * 3 * 6.28);
% **************************************************************
% Set up Farrow resampling
% **************************************************************
nSamplesIn = size(inData.signal, 2);
nSamplesOut = inData.nSamplesOut;
order = size(inData.cMatrix, 1) - 1; % polynomial order
% number of input samples that contribute to one output sample (FIR size)
nTaps = size(inData.cMatrix, 2);
assert(mod(nTaps, inData.nBanks) == 0);
nTaps = nTaps / inData.nBanks; % only one out of nBanks coefficients contributes at any time
% pointer to the position in the input stream for each output sample (row vector, real numbers), starting at 0
inputIndex = (0:nSamplesOut-1) / nSamplesOut * nSamplesIn;
% split into integer part (0..nSamplesIn - 1) ...
inputIndexIntegerPart = floor(inputIndex);
% ... and fractional part [0, 1[
inputIndexFractionalPart = inputIndex - inputIndexIntegerPart;
% bank switching
% the fractional part is again split into an integer and fractional part
inputIndexFractionalPart = inputIndexFractionalPart * inData.nBanks;
inputIndexFractionalPart_int = floor(inputIndexFractionalPart); % coefficient bank index
inputIndexFractionalPart_frac = inputIndexFractionalPart - inputIndexFractionalPart_int; % fractional time 0..1 within each bank
% **************************************************************
% Calculate output stream
% First constant term (conventional FIR), then linear, quadratic, cubic, ...
% **************************************************************
outStream = zeros(1, inData.nSamplesOut);
for ixOrder = 0 : order
% note: fractional time is now defined for each sub-segment [0, 1[
x = inputIndexFractionalPart_frac .^ ixOrder;
% **************************************************************
% Add the contribution of each tap one-by-one
% **************************************************************
for ixTap = 0 : nTaps - 1
% coefficient bank switching: There are inData.nBanks alternative coefficients for each tap
c = inData.cMatrix(ixOrder+1, ixTap * inData.nBanks + inputIndexFractionalPart_int + 1);
% index of input sample that contributes to output via the current tap
% higher tap index => longer delay => older input sample => smaller data index
dataIx = inputIndexIntegerPart - ixTap;
% wrap around
dataIx = mod(dataIx, nSamplesIn);
% array indexing starts at 1
dataIx = dataIx + 1;
delayed = inData.signal(dataIx);
% for each individual output sample (index in row vector),
% - evaluate f = c(order, tapindex) * fracPart .^ order
% - scale the delayed input sample with f
% - accumulate the contribution of all taps
% this implementation performs the operation for all output samples in parallel (row vector)
outStream = outStream + c .* delayed .* x;
end % for ixTap
end % for ixOrder
% **************************************************************
% plot
% **************************************************************
xIn = linspace(0, 1, nSamplesIn + 1); xIn = xIn(1:end-1);
xOut = linspace(0, 1, nSamplesOut + 1); xOut = xOut(1:end-1);
figure(); grid on; hold on;
stem(xIn, inData.signal, 'k+-');
plot(xOut, outStream, 'b+-');
legend('input', 'output');
title('bank-switched Farrow resampling. Signals are cyclic.');Computing Square Root of A Vector of Fixed-Point Numbers
* =========================================================================== *
* *
* Compute square root of a Q.15 vector by 4th order polynomial fitting *
* y[i] = sqrt(x[i]), 0 <= x[i] < 1; *
* *
* C prototype: *
* void DSP_vsqrt_q15(short* x, short* y, int N); *
* *
* Performance: *
* O(4*N) or 4 cycles per number (software pipelining enabled by -O2) *
* *
* Error: *
* (-2^-15, 2^-15) *
* *
* =========================================================================== *
; chebfun, min max error
; 0xFFF1024A = Q31(-0.0005)
; 0x0046E0AB = Q31(0.0022)
; 0xFE764EE1 = Q31(-0.0120)
; 0x1277E288 = Q31(0.1443)
; 0x6ED9EBA1 = Q31(0.8660)
; polyfit, min sqr error
; 0xFFF1203D = Q31(-0.0005)
; 0x004581E7 = Q31(0.0021)
; 0xFE7645AF = Q31(-0.0120)
; 0x1278CF97 = Q31(0.1443)
; 0x6ED9E687 = Q31(0.8660)
SQRT_C4 .set 0xFFF1203D
SQRT_C3 .set 0x004581E7
SQRT_C2 .set 0xFE7645AF
SQRT_C1 .set 0x1278CF97
SQRT_C0 .set 0x6ED9E687
SQRT_S .set 0x5A82799A ; Q31(0.7071)
.sect ".text: _DSP_vsqrt_q15"
.global _DSP_vsqrt_q15
_DSP_vsqrt_q15: .cproc A_X, B_Y, A_n
.no_mdep
.rega A_C4, A_C3, A_C2, A_C1, A_C0, A_xx0, A_rnd, A_y0
.rega A_y0c4, A_y0c3, A_y0c2, A_y0c1, A_x0c3, A_x0c2, A_x0c1, A_x0c0
.rega A_S, A_e0, A_x0x, A_xm, A_y0l, A_y0h, A_y0s
.regb B_C4, B_C3, B_C2, B_C1, B_C0, B_xx1, B_rnd, B_y1, B_y10
.regb B_y1c4, B_y1c3, B_y1c2, B_y1c1, B_x1c3, B_x1c2, B_x1c1, B_x1c0
.regb B_S, B_e1, B_x1x, B_xm, B_y1l, B_y1h, B_y1s, B_X
.reg B_i, C0, C1
ADD 2, A_X, B_X
MVK 0x1, A_rnd
SHL A_rnd, 15, A_rnd
MV A_rnd, B_rnd
MVKL SQRT_C4, A_C4
MVKH SQRT_C4, A_C4
MVKL SQRT_C3, B_C3
MVKH SQRT_C3, B_C3
MV A_C4, B_C4
MV B_C3, A_C3
MVKL SQRT_C2, A_C2
MVKH SQRT_C2, A_C2
MVKL SQRT_C1, B_C1
MVKH SQRT_C1, B_C1
MV A_C2, B_C2
MV B_C1, A_C1
MVKL SQRT_C0, A_C0
MVKH SQRT_C0, A_C0
MVKL SQRT_S, B_S
MVKH SQRT_S, B_S
MV B_S, A_S
MV A_C0, B_C0
MVKL 0x6000, A_xm
SHL A_xm, 16, A_xm
MV A_xm, B_xm
SHR A_n, 1, B_i
SUB B_i, 2, B_i
LOOP_vsqrt: .trip 8
LDH.D1T1 *A_X++[2], A_xx0
LDH.D2T2 *B_X++[2], B_xx1
NORM.L1 A_xx0, A_e0
NORM.L2 B_xx1, B_e1
SSHVL.M1 A_xx0, A_e0, A_x0x
SSHVL.M2 B_xx1, B_e1, B_x1x
SUB.D1 A_e0, 16, A_e0
SUB.D2 B_e1, 16, B_e1
AND.D1 0x1, A_e0, C0
AND.D2 0x1, B_e1, C1
SHR.S1 A_e0, 1, A_e0
SHR.S2 B_e1, 1, B_e1
SUB.D1 A_x0x, A_xm, A_x0x
SUB.D2 B_x1x, B_xm, B_x1x
SHL.S1 A_x0x, 2, A_x0x
SHL.S2 B_x1x, 2, B_x1x
MPYHIR.M1 A_x0x, A_C4, A_y0c4
MPYHIR.M2 B_x1x, B_C4, B_y1c4
SADD.L1 A_y0c4, A_C3, A_x0c3
SADD.L2 B_y1c4, B_C3, B_x1c3
MPYHIR.M1 A_x0x, A_x0c3, A_y0c3
MPYHIR.M2 B_x1x, B_x1c3, B_y1c3
SADD.L1 A_y0c3, A_C2, A_x0c2
SADD.L2 B_y1c3, B_C2, B_x1c2
MPYHIR.M1 A_x0x, A_x0c2, A_y0c2
MPYHIR.M2 B_x1x, B_x1c2, B_y1c2
SADD.L1 A_y0c2, A_C1, A_x0c1
SADD.L2 B_y1c2, B_C1, B_x1c1
MPYHIR.M1 A_x0x, A_x0c1, A_y0c1
MPYHIR.M2 B_x1x, B_x1c1, B_y1c1
SADD.L1 A_y0c1, A_C0, A_x0c0
SADD.L2 B_y1c1, B_C0, B_x1c0
; A_S = B_S = 0x5A82799A ~= 0x5A820000 + 0x00008000
[C0] MPYHIR.M1 A_S, A_x0c0, A_y0h
[C1] MPYHIR.M2 B_S, B_x1c0, B_y1h
[C0] SHR A_x0c0, 16, A_y0l
[C1] SHR B_x1c0, 16, B_y1l
[C0] SADD.L1 A_y0h, A_y0l, A_x0c0
[C1] SADD.L2 B_y1h, B_y1l, B_x1c0
SHR.S1 A_x0c0, A_e0, A_y0s
SHR.S2 B_x1c0, B_e1, B_y1s
SADD.L1 A_y0s, A_rnd, A_y0
SADD.L2 B_y1s, B_rnd, B_y1
PACKH2.S2X B_y1, A_y0, B_y10
STW.D2T2 B_y10, *B_Y++
BDEC LOOP_vsqrt, B_i
.endprocExponential Audio Unmute
function [y] = signal_unmute(x, index, duration, Fs)
% Return the input vector with a unmute that occurs at a specific
% index and with an exponential ramp-up to reduce "pop" sounds.
% The output will start off at -100dB gain and end at 0dB gain.
%
% Usage: y = SIGNAL_UNMUTE(x, index, duration, Fs);
%
% X is your one-dimensional input array
% INDEX is where in the input signal you want the unmute to begin
% DURATION is how long (in seconds) to exponentially ramp up the
% input signal. 100ms is recommended.
% FS is the sample rate
%
% Example:
% You want to unmute your signal at 0.5sec with a duration of 100ms
% and with a 48k Fs. (signal is unmuted completely at 0.6sec)
% y = signal_mute(x, 24000, 0.1, 48000);
%
% Author: sparafucile17 7/29/2003
% Input must have some length
if(length(x) == 1)
error('ERROR: input signal must have more than one element');
end
% This function only supports one-dimensional arrays
if((size(x, 2) ~= 1) && (size(x, 1) ~= 1))
error('ERROR: Input must be one-dimensional');
end
% Make sure there are enough samples to complete the mute
if(length(x) < (index + duration*Fs))
error(['There are not enough samples in X to complete the unmute. ' ...
'Either change the mute duration or move the index back.' ]);
end
% Flip vector (temporarily)
if((size(x, 2) ~= 1))
x = x';
flip_back = true;
else
flip_back = false;
end
% Calculate exponential coefficient
dB_atten = -100; %What do we consider "muted" to be in decibels
decayrate = -dB_atten / duration;
coeff = 1.0 - 10^(-decayrate/(20.0*Fs));
% Build the Gain array
gain = [zeros(index, 1); ones((length(x)-index), 1);];
b = [ coeff 0];
a = [ 1 (-1*(1-coeff))];
gain = filter(b,a,gain);
% Apply Mute (gain) to the input signal
y = gain .* x;
% Flip the vector (if required)
if(flip_back == true);
y = y';
endImage Denoising -threshold calculation using modified bivariate method
function [T,sigma1,sigma2] = model3_soft(CD,CH,CH1)
%function used to calculate the threshold and variance using modified
%bivariate model
%CD and CH : obtained after first stage wavelet decomposition
%CH1: obtained after second stage 2D-wavelet decomposition
sigman = (median(median(abs(CD))))/0.6745;
sigmay1 = 0;
sigmay2 = 0;
[m,n] = size(CD);
[m1,n1] = size(CH1);
%To calculate sigma1 value
for i =1:m
for j = 1:n
sigmay1 = sigmay1+((CH(i,j))^2);
end
end
sigmay1 = sqrt(2)*sigmay1/(m*n);
sigma1 = sqrt(max((((sigmay1))-((sigman)^2)),0));
if sigma1~=0
T = sqrt(3)*(sigman^2);
else
T = max(max(abs(CH)));
end
%To calculate sigma2 value
for i =1:m1
for j = 1:n1
sigmay2 = sigmay2+((CH1(i,j))^2);
end
end
sigmay2 = sqrt(2)*sigmay2/(m1*n1);
sigma2 = sqrt(max((((sigmay2))-((sigman)^2)),0));Duobianry Signaling-Amplitude & Phase Response
function [Amplitude_Response,Phase_Response]= Duobinary_Signaling()
//Duobinary Signaling Scheme
//Magnitude and Phase Response
rb = input('Enter the bit rate=');
Tb =1/rb; //Bit duration
f = -rb/2:1/100:rb/2;
Amplitude_Response = abs(2*cos(%pi*f.*Tb));
Phase_Response = -(%pi*f.*Tb);
subplot(2,1,1)
a=gca();
a.x_location ="origin";
a.y_location ="origin";
plot(f,Amplitude_Response)
xlabel('Frequency f---->')
ylabel('|H(f)| ----->')
title('Amplitude Repsonse of Duobinary Singaling')
subplot(2,1,2)
a=gca();
a.x_location ="origin";
a.y_location ="origin";
plot(f,Phase_Response)
xlabel(' Frequency f---->')
ylabel(' <H(f) ----->')
title('Phase Repsonse of Duobinary Singaling')
endfunction
//Result
//-->exec('C:\Users\SENTHILKUMAR\Desktop\Communication_Toolbox\Digital_Communication\New folder\Duobinary_Signaling.sci', -1)
//
//-->[Amplitude_Response,Phase_Response]= Duobinary_Signaling()
//Enter the bit rate= 8Power Spectrum of Discrete PAM signals
function [Sxxf_NRZ_P,Sxxf_NRZ_BP,Sxxf_NRZ_UP,Sxxf_Manch]=PowerSpectra_PAM()
a = input('Enter the Amplitude value:');
fb = input('Enter the bit rate:');
Tb = 1/fb; //bit duration
f = 0:1/(100*Tb):2/Tb;
for i = 1:length(f)
Sxxf_NRZ_P(i) = (a^2)*Tb*(sinc_new(f(i)*Tb)^2);
Sxxf_NRZ_BP(i) = (a^2)*Tb*((sinc_new(f(i)*Tb))^2)*((sin(%pi*f(i)*Tb))^2);
if (i==1)
Sxxf_NRZ_UP(i) = (a^2)*(Tb/4)*((sinc_new(f(i)*Tb))^2)+(a^2)/4;
else
Sxxf_NRZ_UP(i) = (a^2)*(Tb/4)*((sinc_new(f(i)*Tb))^2);
end
Sxxf_Manch(i) = (a^2)*Tb*(sinc_new(f(i)*Tb/2)^2)*(sin(%pi*f(i)*Tb/2)^2);
end
//Plotting
a = gca();
plot2d(f,Sxxf_NRZ_P)
poly1= a.children(1).children(1);
poly1.thickness = 2; // the tickness of a curve.
plot2d(f,Sxxf_NRZ_BP,2)
poly1= a.children(1).children(1);
poly1.thickness = 2; // the tickness of a curve.
plot2d(f,Sxxf_NRZ_UP,5)
poly1= a.children(1).children(1);
poly1.thickness = 2; // the tickness of a curve.
plot2d(f,Sxxf_Manch,9)
poly1= a.children(1).children(1);
poly1.thickness = 2; // the tickness of a curve.
xlabel('f*Tb------->')
ylabel('Sxx(f)------->')
title('Power Spectral Densities of Different Line Codinig Techniques')
xgrid(1)
legend(['NRZ Polar Format','NRZ Bipolar format','NRZ Unipolar format','Manchester format']);
endfunction
//Result
//Enter the Amplitude value:1
//Enter the bit rate:1Power spectra of MSK & QPSk
function [SB_MSK,SB_QPSK]= PowerSpectra_MSK_QPSK()
//Comparison of QPSK and MSK Power Spectrums
rb = input('Enter the bit rate in bits per second:');
Eb = input('Enter the Energy of bit:');
f = 0:1/(100*rb):(4/rb);
Tb = 1/rb; //bit duration in seconds
for i = 1:length(f)
if(f(i)==0.5)
SB_MSK(i) = 4*Eb*f(i);
else
SB_MSK(i) = (32*Eb/(%pi^2))*(cos(2*%pi*Tb*f(i))/((4*Tb*f(i))^2-1))^2;
end
SB_QPSK(i)= 4*Eb*sinc_new((2*Tb*f(i)))^2;
end
a = gca();
plot(f*Tb,SB_MSK/(4*Eb));
plot(f*Tb,SB_QPSK/(4*Eb));
poly1= a.children(1).children(1);
poly1.foreground = 3;
xlabel('Normalized Frequency ---->')
ylabel('Normalized Power Spectral Density--->')
title('QPSK Vs MSK Power Spectra Comparison')
legend(['Minimum Shift Keying','QPSK'])
xgrid(1)
endfunction
//Result
//Enter the bit rate in bits per second:2
//Enter the Energy of bit:1Fast SIMD sine and cosine
// Fast sine and cosine for SHARC ADSP-21364, callable from VisualDSP++ C.
// Simultaneously compute sine and cosine of a given angle.
// Polynomial approximation developed by Flemming Pedersen of CERN.
// This implementation by Lippold Haken of Haken Audio, March 2010, October 2012.
//
// C prototype for this function:
// typedef struct { float sin, cos; } SinCos;
// void sinCos( float fRadians, SinCos *result );
//
// 23 cycles to execute this function:
// 18 cycles for the computations
// 5 cycles for compiler environment overhead.
#include <def21364.h>
// Data table for sinCos function.
.section/dm/DOUBLE32 seg_dmda;
sinCosData:
.global sinCosData;
.type sinCosData,STT_OBJECT;
.var =
// Integer 3 for "mod 4" operation.
0x00000003, 0x00000003,
// 1.0 for neutralizing final cos multiply.
0x3F800000, 0x3F800000,
// Coefficients for sin and cos polynomials.
0xBB96BD89, // SQ7 for sin polynomial -4.6002309092153379e-003
0xBCA75707, // CQ6 for cos polynomial -2.0427240364907607e-002
0x3DA32F1D, // SQ5 for sin polynomial 7.9679708649230657e-002
0x3E81D8BD, // CQ4 for cos polynomial 2.5360671639164339e-001
0xBF255DDD, // SQ3 for sin polynomial -6.4596348437163809e-001
0xBF9DE9D1, // CQ2 for cos polynomial -1.2336979844380824e+000
0x3FC90FDB, // SQ1 for sin polynomial 1.5707963267948966e+000
0x3F800000, // CQ0 for cos polynomial 1.0000000000000000e+000
// Sign adjustment table, indexed by integer quadrant.
0x3F800000, 0x3F800000, // 1.0, 1.0
0x3F800000, 0xBF800000, // 1.0,-1.0
0xBF800000, 0xBF800000, // -1.0,-1.0
0xBF800000, 0x3F800000; // -1.0, 1.0
sinCosData.end:
.section/pm/DOUBLE32 seg_pmco;
_sinCos:
// Registers in VisualDSP environment:
// M5,M13 = 0
// M6,M14 = 1
// M7,M15 = -1
// F4 = first function argument (input angle)
// R8 = pointer to address for storing sin,cos result
// R0,R1,R2,R4,R8,R12,I4,I12,I13,M4 need not be preserved
// I6,I7 = stack and frame pointers
// C calling routine has: "CJUMP (DB); DM(I7,M7)=R2; DM(I7,M7)=PC;"
// CJUMP does these operations: "R2=I6, I6=I7"
// Before exiting must do RFRAME: "I7=I6, I6=DM(0,I6)"
// Preamble.
SF4 = F4;
BIT SET MODE1 SIMD;
// Pointer to constants.
I4 = sinCosData;
// Compute integer quadrant, fractional quadrant, fractional quadrant squared.
// Quadrant "q" = fRadians * 2./Pi
// Quadrant values (0. .. 4.) correspond to (0. .. 2Pi)
R1 = 0x3F22F983; // F1 = 2./Pi
F0 = F1 * F4, I12 = DM(M7,I6); // I12 is execution return address
// Integer quadrant = round(q) mod 4 (0..3)
// Since MODE1 TRUNC bit is zero, FIX implements round-to-nearest.
R1 = FIX F0, R2 = DM(I4,2);
R2 = R1 AND R2, F12 = DM(I4,2);
// Fractional quadrant "Xq" = q - round(q) (-.5 .. .5)
// Fractional quadrant values (-.5 .. .5) correspond to (-Pi/4..Pi/4)
F1 = FLOAT R1, F4 = DM(I4,2);
F1 = F0 - F1, M4 = R2;
// Set SZ if integer quadrant is even.
R2 = LSHIFT R2 BY 31;
// Fractional quadrant squared "Xq2" = Xq * Xq
// Set SF1 = 1.0 to avoid final Xq multiply for cosine polynomial.
F2 = F1 * F1, F12 <-> SF1;
// Registers involved in sin and cos computation:
// F1 = fractional quadrant Xq
// SF1 = 1.0
// F2,SF2 = fractional quadrant squared Xq2
// F4 = SQ7
// SF4 = CQ6
// M4 = integer quadrant
// SZ = indicates integer quadrant is even
// DM(I4) = pairs of cosine and sine coefficients
// Compute sine polynomial (PEx) and cosine polynomial (PEy).
// Xq2*SQ7 Xq2*CQ6
F0 = F2 * F4, F4 = DM(I4,2);
// SQ5+Xq2*SQ7 CQ4+Xq2*CQ6
F0 = F0 + F4;
// Xq2(SQ5+Xq2*SQ7) Xq2(CQ4+Xq2*CQ6)
F0 = F0 * F2, F4 = DM(I4,2);
// SQ3+Xq2(SQ5+Xq2*SQ7) CQ2+Xq2(CQ4+Xq2*CQ6)
F0 = F0 + F4, F4 = DM(I4,2);
// Xq2(SQ3+Xq2(SQ5+Xq2*SQ7)) Xq2(CQ2+Xq2(CQ4+Xq2*CQ6))
F0 = F0 * F2, MODIFY(I4,M4);
// SQ1+Xq2(SQ3+Xq2(SQ5+Xq2*SQ7))) CQ0+Xq2(CQ2+Xq2(CQ4+Xq2*CQ6)))
F0 = F0 + F4, F4 = DM(M4,I4);
// Xq(SQ1+Xq2(SQ3+Xq2(SQ5+Xq2*SQ7)))) no change on PEy
F0 = F0 * F1, I4 = R8; // I4 is data return address
// Registers:
// F0 = sine result so far
// SF0 = cosine result so far
// F4,SF4 = +/-1 for inverting sign for quadrant
// SZ = set for integer quadrant even
// Invert and swap sin/cos according to integer quadrant:
// quadrant F0 SF0
// 0 = 00 SIN COS
// 1 = 01 COS -SIN swap results, invert sine
// 2 = 10 -SIN -COS invert signs
// 3 = 11 -COS SIN swap results, invert cosine
IF NOT SZ F0 <-> SF0; // swap sin,cos if odd quadrant
RFRAME; // stack frame management before exit
JUMP (M14,I12) (DB), F0 = F0 * F4; // negate sin/cos if needed
DM(M5,I4) = F0; // store sin at I4, cos (SF0) at I4+1
BIT CLR MODE1 SIMD; // end SIMD during JUMP (DB) stall
._sinCos.end:
.global _sinCos;
.type _sinCos,STT_FUNC;Fast power-of-10 approximation, for 32-bit floats
// Fast power-of-10 approximation, with RMS error of 1.77%.
// This approximation developed by Nicol Schraudolph (Neural Computation vol 11, 1999).
// Adapted for 32-bit floats by Lippold Haken of Haken Audio, April 2010.
// Set float variable's bits to integer expression.
// f=b^f is approximated by
// (int)f = f*0x00800000*log(b)/log(2) + 0x3F800000-60801*8
// f=10^f is approximated by
// (int)f = f*27866352.6 + 1064866808.0
inline void Pow10(float *f) { *(int *)f = *f * 27866352.6 + 1064866808.0; };Inverse Sqrt and Fourth Root approximations
// Fast InvSqrt approxumation, with an error of less than 4%.
// This approximation is attributed to Greg Walsh.
inline void InvSqrt(float *x) { *(int *)x = 0x5f3759df - (*(int *)x >> 1); }
inline float SqrtSqrt(float x) { InvSqrt(&x); InvSqrt(&x); return x; }Fast SIMD sine and cosine
// Fast sine and cosine for SHARC ADSP-21364, callable from VisualDSP++ C.
// Simultaneously compute sine and cosine of a given angle.
// Polynomial approximation developed by Flemming Pedersen of CERN.
// This implementation by Lippold Haken of Haken Audio, March 2010, October 2012.
//
// C prototype for this function:
// typedef struct { float sin, cos; } SinCos;
// void sinCos( float fRadians, SinCos *result );
//
// 23 cycles to execute this function:
// 18 cycles for the computations
// 5 cycles for compiler environment overhead.
#include <def21364.h>
// Data table for sinCos function.
.section/dm/DOUBLE32 seg_dmda;
sinCosData:
.global sinCosData;
.type sinCosData,STT_OBJECT;
.var =
// Integer 3 for "mod 4" operation.
0x00000003, 0x00000003,
// 1.0 for neutralizing final cos multiply.
0x3F800000, 0x3F800000,
// Coefficients for sin and cos polynomials.
0xBB96BD89, // SQ7 for sin polynomial -4.6002309092153379e-003
0xBCA75707, // CQ6 for cos polynomial -2.0427240364907607e-002
0x3DA32F1D, // SQ5 for sin polynomial 7.9679708649230657e-002
0x3E81D8BD, // CQ4 for cos polynomial 2.5360671639164339e-001
0xBF255DDD, // SQ3 for sin polynomial -6.4596348437163809e-001
0xBF9DE9D1, // CQ2 for cos polynomial -1.2336979844380824e+000
0x3FC90FDB, // SQ1 for sin polynomial 1.5707963267948966e+000
0x3F800000, // CQ0 for cos polynomial 1.0000000000000000e+000
// Sign adjustment table, indexed by integer quadrant.
0x3F800000, 0x3F800000, // 1.0, 1.0
0x3F800000, 0xBF800000, // 1.0,-1.0
0xBF800000, 0xBF800000, // -1.0,-1.0
0xBF800000, 0x3F800000; // -1.0, 1.0
sinCosData.end:
.section/pm/DOUBLE32 seg_pmco;
_sinCos:
// Registers in VisualDSP environment:
// M5,M13 = 0
// M6,M14 = 1
// M7,M15 = -1
// F4 = first function argument (input angle)
// R8 = pointer to address for storing sin,cos result
// R0,R1,R2,R4,R8,R12,I4,I12,I13,M4 need not be preserved
// I6,I7 = stack and frame pointers
// C calling routine has: "CJUMP (DB); DM(I7,M7)=R2; DM(I7,M7)=PC;"
// CJUMP does these operations: "R2=I6, I6=I7"
// Before exiting must do RFRAME: "I7=I6, I6=DM(0,I6)"
// Preamble.
SF4 = F4;
BIT SET MODE1 SIMD;
// Pointer to constants.
I4 = sinCosData;
// Compute integer quadrant, fractional quadrant, fractional quadrant squared.
// Quadrant "q" = fRadians * 2./Pi
// Quadrant values (0. .. 4.) correspond to (0. .. 2Pi)
R1 = 0x3F22F983; // F1 = 2./Pi
F0 = F1 * F4, I12 = DM(M7,I6); // I12 is execution return address
// Integer quadrant = round(q) mod 4 (0..3)
// Since MODE1 TRUNC bit is zero, FIX implements round-to-nearest.
R1 = FIX F0, R2 = DM(I4,2);
R2 = R1 AND R2, F12 = DM(I4,2);
// Fractional quadrant "Xq" = q - round(q) (-.5 .. .5)
// Fractional quadrant values (-.5 .. .5) correspond to (-Pi/4..Pi/4)
F1 = FLOAT R1, F4 = DM(I4,2);
F1 = F0 - F1, M4 = R2;
// Set SZ if integer quadrant is even.
R2 = LSHIFT R2 BY 31;
// Fractional quadrant squared "Xq2" = Xq * Xq
// Set SF1 = 1.0 to avoid final Xq multiply for cosine polynomial.
F2 = F1 * F1, F12 <-> SF1;
// Registers involved in sin and cos computation:
// F1 = fractional quadrant Xq
// SF1 = 1.0
// F2,SF2 = fractional quadrant squared Xq2
// F4 = SQ7
// SF4 = CQ6
// M4 = integer quadrant
// SZ = indicates integer quadrant is even
// DM(I4) = pairs of cosine and sine coefficients
// Compute sine polynomial (PEx) and cosine polynomial (PEy).
// Xq2*SQ7 Xq2*CQ6
F0 = F2 * F4, F4 = DM(I4,2);
// SQ5+Xq2*SQ7 CQ4+Xq2*CQ6
F0 = F0 + F4;
// Xq2(SQ5+Xq2*SQ7) Xq2(CQ4+Xq2*CQ6)
F0 = F0 * F2, F4 = DM(I4,2);
// SQ3+Xq2(SQ5+Xq2*SQ7) CQ2+Xq2(CQ4+Xq2*CQ6)
F0 = F0 + F4, F4 = DM(I4,2);
// Xq2(SQ3+Xq2(SQ5+Xq2*SQ7)) Xq2(CQ2+Xq2(CQ4+Xq2*CQ6))
F0 = F0 * F2, MODIFY(I4,M4);
// SQ1+Xq2(SQ3+Xq2(SQ5+Xq2*SQ7))) CQ0+Xq2(CQ2+Xq2(CQ4+Xq2*CQ6)))
F0 = F0 + F4, F4 = DM(M4,I4);
// Xq(SQ1+Xq2(SQ3+Xq2(SQ5+Xq2*SQ7)))) no change on PEy
F0 = F0 * F1, I4 = R8; // I4 is data return address
// Registers:
// F0 = sine result so far
// SF0 = cosine result so far
// F4,SF4 = +/-1 for inverting sign for quadrant
// SZ = set for integer quadrant even
// Invert and swap sin/cos according to integer quadrant:
// quadrant F0 SF0
// 0 = 00 SIN COS
// 1 = 01 COS -SIN swap results, invert sine
// 2 = 10 -SIN -COS invert signs
// 3 = 11 -COS SIN swap results, invert cosine
IF NOT SZ F0 <-> SF0; // swap sin,cos if odd quadrant
RFRAME; // stack frame management before exit
JUMP (M14,I12) (DB), F0 = F0 * F4; // negate sin/cos if needed
DM(M5,I4) = F0; // store sin at I4, cos (SF0) at I4+1
BIT CLR MODE1 SIMD; // end SIMD during JUMP (DB) stall
._sinCos.end:
.global _sinCos;
.type _sinCos,STT_FUNC;Fractional Delay Line implementation
/****************DELAY.C*******************************/
#include "delay.h"
#include "math.h"
#define MAX_BUF_SIZE 64000
/*****************************************************************************
* Fractional delay line implementation in C:
*
* ---------[d_mix]--------------------------
* | |
* | |
* |x1 v
* xin ------>[+]----->[z^-M]--[interp.]----[d_fw]-------->[+]-----> yout
* ^ |
* | |
* |----------[d_fb]<--------|
*******************************************************************************/
double d_buffer[MAX_BUF_SIZE];
/*
This interface defines the delay object
*/
static struct fract_delay {
double d_mix; /*delay blend parameter*/
short d_samples; /*delay duration in samples*/
double d_fb; /*feedback volume*/
double d_fw; /*delay tap mix volume*/
double n_fract; /*fractional part of the delay*/
double *rdPtr; /*delay read pointer*/
double *wrtPtr; /*delay write pointer*/
};
static struct fract_delay del;
/*
This function is used to initialize the delay object
*/
void Delay_Init(double delay_samples,double dfb,double dfw, double dmix) {
Delay_set_delay(delay_samples);
Delay_set_fb(dfb);
Delay_set_fw(dfw);
Delay_set_mix(dmix);
del.wrtPtr = &d_buffer[MAX_BUF_SIZE-1];
}
/*
These functions are used as interface to the delay object,
so there's not direct access to the delay object from
external modules
*/
void Delay_set_fb(double val) {
del.d_fb = val;
}
void Delay_set_fw(double val) {
del.d_fw = val;
}
void Delay_set_mix(double val) {
del.d_mix = val;
}
void Delay_set_delay(double n_delay) {
/*Get the integer part of the delay*/
del.d_samples = (short)floor(n_delay);
/*gets the fractional part of the delay*/
del.n_fract = (n_delay - del.d_samples);
}
double Delay_get_fb(void) {
return del.d_fb;
}
double Delay_get_fw(void) {
return del.d_fw;
}
double Delay_get_mix(void) {
return del.d_mix;
}
/*
This is the main delay task,
*/
double Delay_task(double xin) {
double yout;
double * y0;
double * y1;
double x1;
double x_est;
/*Calculates current read pointer position*/
del.rdPtr = del.wrtPtr - (short)del.d_samples;
/*Wraps read pointer*/
if (del.rdPtr < d_buffer) {
del.rdPtr += MAX_BUF_SIZE-1;
}
/*Linear interpolation to estimate the delay + the fractional part*/
y0 = del.rdPtr-1;
y1 = del.rdPtr;
if (y0 < d_buffer) {
y0 += MAX_BUF_SIZE-1;
}
x_est = (*(y0) - *(y1))*del.n_fract + *(y1);
/*Calculate next value to store in buffer*/
x1 = xin + x_est*del.d_fb;
/*Store value in buffer*/
*(del.wrtPtr) = x1;
/*Output value calculation*/
yout = x1*del.d_mix + x_est*del.d_fw;
/*Increment delat write pointer*/
del.wrtPtr++;
/*Wraps delay write pointer*/
if ((del.wrtPtr-&d_buffer[0]) > MAX_BUF_SIZE-1) {
del.wrtPtr = &d_buffer[0];
}
return yout;
}
/***********DELAY.h*************************************/
#ifndef __DELAY_H__
#define __DELAY_H__
void Delay_Init(double delay_samples,double dfb,double dfw, double dmix);
void Delay_set_fb(double val);
void Delay_set_fw(double val);
void Delay_set_mix(double val);
void Delay_set_delay(double n_delay);
double Delay_get_fb(void);
double Delay_get_fw(void);
double Delay_get_mix(void);
double Delay_task(double xin);
#endif
/*****USAGE EXAMPLE****************************************/
void main(void) {
double xin;
double yout;
Delay_Init(85.6,0.7,0.7,1);
while(1) {
if (new_sample_flag()) {
/*When there's new sample at your ADC or CODEC input*/
/*Read the sample*/
xin = read_sample();
/*Apply the Delay_task function to the sample*/
yout = Delay_task(xin);
/*Send the output value to your ADC or codec output*/
write_output(yout);
}
}
}TI C281x Timer Configuration
**********************************************************************/
#include "DSP281x_Device.h"
/**********************************************************************
* Function: InitTimer()
*
* Description: Initialize the CPU Timer 0 at a rate of 2 Hz
**********************************************************************/
void InitTimer(void)
{
//CpuTimer0Regs.TIM.all = 0x0; //Timer0 Counter Register
CpuTimer0Regs.PRD.all = 0x047868C0; //Period Register
CpuTimer0Regs.TCR.all = 0x4830; //Control Register
/*
bit 15 0: CPU-Timer Interupt Flag
bit 14 1: Timer Interrupt Enable
bit 13-12 0's: Reserved
bit 11-10 10: CPU-Timer Emulation Modes
bit 9-6 0's: Reserved
bit 5 0: CPU-Timer Reload bit
bit 4 0: CPU-Timer Status Bit
bit 3-0 0's: Reserved
*/
CpuTimer0Regs.TPR.all = 0x0000; //Prescale Register
CpuTimer0Regs.TPRH.all = 0x0000; //Prescale Register High
PieCtrlRegs.PIEIER1.bit.INTx7 = 1; //Interruption enabled
IER |= 0x0001; //PIE group enabled
StartCpuTimer0();//Reset of the Timer
}Basic Kalman filter
// Clear initialisation
clf()
// Time vector
t =[0:0.5:100];
len_t = length(t);
dt = 100 / len_t;
// Real values x: position v: velocity a: acceleration
x_vrai = 0 * t;
v_vrai = 0 * t;
a_vrai = 0 * t;
// Meseared values.
x_mes = 0 * t;
v_mes = 0 * t;
a_mes = 0 * t;
// Initialisation
for i = 0.02 * len_t: 0.3 * len_t,
a_vrai(i) = 1;
end
for i = 0.5 * len_t: 0.7 * len_t,
a_vrai(i) = 2;
end
// State of kalman filter
etat_vrai = [ x_vrai(1); v_vrai(1); a_vrai(1) ];
A = [ 1 dt dt*dt/2; 0 1 dt; 0 0 1];//transition matrice
for i = 2:length(t),
etat_vrai = [ x_vrai(i-1); v_vrai(i-1); a_vrai(i) ];
etat_vrai = A * etat_vrai;
x_vrai(i) = etat_vrai(1);
v_vrai(i) = etat_vrai(2);
end
max_brt_x = 200;
max_brt_v = 10;
max_brt_a = 0.3;
// Random noise
x_brt = grand(1, len_t, 'unf', -max_brt_x, max_brt_x);
v_brt = grand(1, len_t, 'unf', -max_brt_v, max_brt_v);
a_brt = grand(1, len_t, 'unf', -max_brt_a, max_brt_a);
// Compute meas
x_mes = x_vrai + x_brt;
v_mes = v_vrai + v_brt;
a_mes = a_vrai + a_brt;
// START
x_est = 0 * t;
v_est = 0 * t;
a_est = 0 * t;
etat_mes = [ 0; 0; 0 ];
etat_est = [ 0; 0; 0 ];
inn = [ 0; 0; 0 ];
// Matrix of covariance of the bruit.
// independant noise -> null except for diagonal,
// and on the diagonal == sigma^2.
// VAR(aX+b) = a^2 * VAR(X);
// VAR(X) = E[X*X] - E[X]*E[X]
R = [ max_brt_x*max_brt_x 0 0; 0 max_brt_v*max_brt_v 0; 0 0 max_brt_a*max_brt_a ];
Q = [1 0 0; 0 1 0; 0 0 1];
P = Q;
for i = 2:length(t),
// Init : measured state
etat_mes = [ x_mes(i); v_mes(i); a_mes(i) ];
// Innovation: measured state - estimated state
inn = etat_mes - etat_est;
// Covariance of the innovation
S = P + R;
// Gain
K = A * inv(S);
// Estimated state
etat_est = A * etat_est + K * inn;
// Covariance of prediction error
// C = identity
P = A * P * A' + Q - A * P * inv(S) * P * A';
// End: estimated state
x_est(i) = etat_est(1);
v_est(i) = etat_est(2);
a_est(i) = etat_est(3);
end
// Blue : real
// Gree : noised
// Red: estimated
subplot(311)
plot(t, a_vrai, t, a_mes, t, a_est);
subplot(312)
plot(t, v_vrai, t, v_mes, t, v_est);
subplot(313)
plot(t, x_vrai, t, x_mes, t, x_est);Block processing adaptative notch filter
bool Do(const Audio& input, const Audio& reference, Audio& output)
{
const unsigned size = input.GetSize();
const DataArray& in = input.GetBuffer();
const DataArray& ref = reference.GetBuffer();
DataArray& out = output.GetBuffer();
const unsigned M = mConfig.GetFilterLength();
const TData mu = mConfig.GetStep();
const unsigned L = M-1;
std::vector<TData> &wn = _filterCoef;
TData r[M];
for (unsigned k=0;k<size;k++)
{
TData acum = 0.;
for (unsigned n=0, i=k;n<M;n++,i++)
{
if (i<L)
r[n] = _oldRef[i];
else
r[n] = ref[i-L];
acum += wn[n]*r[n]; // interference estimation
}
if (k<L)
out[k] = _oldIn[k]-acum; // ECG signal estimation
else
out[k] = in[k-L]-acum; // ECG signal estimation
for (unsigned n=0;n<M;n++) wn[n]+=mu*r[n]*out[k]; // new filter taps
}
for (unsigned k=0;k<L;k++)
{
_oldRef[k] = ref[size-L+k];
_oldIn[k] = in[size-L+k];
}
return true;
}Resampling based on FFT
% FFTRESAMPLE Resample a real signal by the ratio p/q
function y = fftResample(x,p,q)
% --- take FFT of signal ---
f = fft(x);
% --- resize in the FFT domain ---
% add/remove the highest frequency components such that len(f) = len2
len1 = length(f);
len2 = round(len1*p/q);
lby2 = 1+len1/2;
if len2 < len1
% remove some high frequency samples
d = len1-len2;
f = f(:);
f(floor(lby2-(d-1)/2:lby2+(d-1)/2)) = [];
elseif len2 > len1
% add some high frequency zero samples
d = len2-len1;
lby2 = floor(lby2);
f = f(:);
f = [f(1:lby2); zeros(d,1); f(lby2+1:end)];
end
% --- take the IFFT ---
% odd number of sample removal/addition may make the FFT of a real signal
% asymmetric and artificially introduce imaginary components - we take the
% real value of the IFFT to remove these, at the cost of not being able to
% reample complex signals
y = real(ifft(f));2-D Ping Pong Game.
%By vkc
function RunGame
hMainWindow = figure(...
'Color', [1 1 1],...
'Name', 'Game Window',...
'Units', 'pixels',...
'Position',[100 100 800 500]);
img = imread('ball.bmp','bmp');
[m,n,c] = size(img);
hBall = axes(...
'parent', hMainWindow,...
'color', [1 1 1],...
'visible', 'off',...
'units', 'pixels',...
'position', [345, 280, n, m] );
hBallImage = imshow( img );
set(hBallImage, 'parent', hBall, 'visible', 'off' );
ballSpeed = 3;
ballDirection = 0;
hTempBall = axes( ...
'parent', hMainWindow,...
'units', 'pixels',...
'color', 'none',...
'visible', 'off',...
'position', get(hBall, 'position' ) );
img = imread('paddle.bmp','bmp');
[m,n,c] = size(img);
hRightPaddle = axes(...
'parent', hMainWindow,...
'color', 'none',...
'visible', 'off',...
'units', 'pixels',...
'position', [650 - 10, 250 - 50, n, m] );
hRightPaddleImage = imshow( img );
set(hRightPaddleImage, 'parent', hRightPaddle, 'visible', 'off' );
targetY = 200;
t = timer( 'TimerFcn', @UpdateRightPaddleAI,...
'StartDelay', 10 );
start(t)
hLeftPaddle = axes(...
'parent', hMainWindow,...
'color', 'none',...
'visible', 'off',...
'units', 'pixels',...
'position', [50, 250 - 50, n, m] );
hLeftPaddleImage = imshow( img );
set(hLeftPaddleImage, 'parent', hLeftPaddle, 'visible', 'off' );
hBottomWall = axes(...
'parent', hMainWindow,...
'color', [1 1 1],...
'units', 'pixels',...
'visible', 'off',...
'position', [0 40 700 10] );
patch( [0 700 700 0], [0 0 10 10], 'b' );
hTopWall = axes(...
'parent', hMainWindow,...
'color', [1 1 1],...
'units', 'pixels',...
'visible', 'off',...
'position', [0 450 700 10] );
patch( [0 700 700 0], [0 0 10 10], 'b' );
rightScore = 0;
leftScore = 0;
hRightScore = axes(...
'parent', hMainWindow,...
'color', 'none',...
'visible', 'off',...
'units', 'pixels',...
'position', [650 485 50 10] );
hLeftScore = axes(...
'parent', hMainWindow,...
'color', 'none',...
'visible', 'off',...
'units', 'pixels',...
'position', [30 485 50 10] );
hRightScoreText = text( 0, 0, '0', 'parent', hRightScore,...
'visible', 'on', 'color', [1 1 1] );
hLeftScoreText = text( 0, 0, '0', 'parent', hLeftScore,...
'visible', 'on', 'color', [1 1 1] );
hQuitButton = uicontrol(...
'string', 'Quit',...
'position', [325 475 50 20],...
'Callback', @QuitButton_CallBack );
hStartButton = uicontrol(...
'string', 'Start',...
'position', [325 240 50 20],...
'Callback',@StartButton_CallBack );
playing = true;
while playing == true
UpdateBall()
UpdateLeftPaddle()
UpdateRightPaddle()
CheckForScore()
pause( 0.01 )
end
stop(t)
close( hMainWindow )
function UpdateBall
pos = get( hBall, 'position' );
ballX = pos(1,1);
ballY = pos(1,2);
ballDirection = NormalizeAngle( ballDirection );
% check for collisions with the walls
if ( ballY > 450 - 10 ) && ( ballDirection > 0 ) && ( ballDirection < 180 )
if ( ballDirection > 90 )
ballDirection = ballDirection + 2 * ( 180 - ballDirection );
else
ballDirection = ballDirection - 2 * ballDirection;
end
elseif ( ballY < 50 ) && ( ballDirection > 180 ) && ( ballDirection < 360 )
if ( ballDirection > 270 )
ballDirection = ballDirection + 2 * ( 360 - ballDirection );
else
ballDirection = ballDirection - 2 * ( ballDirection - 180 );
end
end
% check for collisions with the paddles
if ( ballDirection > 90 && ballDirection < 270 )
leftPaddlePos = get( hLeftPaddle, 'position' );
leftX = leftPaddlePos(1,1);
leftY = leftPaddlePos(1,2);
if( (ballX < leftX + 10)...
&& (ballX > leftX + 5)...
&& (ballY + 10 > leftY)...
&& (ballY < leftY + 100) )
if ( ballDirection < 180 )
ballDirection = 180 - ballDirection;
elseif( ballDirection > 180 )
ballDirection = 180 - ballDirection;
end
end
else
rightPaddlePos = get( hRightPaddle, 'position' );
rightX = rightPaddlePos(1,1);
rightY = rightPaddlePos(1,2);
if( (ballX + 10 > rightX)...
&& (ballX + 10 < rightX + 5)...
&& (ballY > rightY)...
&& (ballY < rightY + 100) )
if ( ballDirection < 90 )
ballDirection = 180 - ballDirection;
elseif( ballDirection > 270 )
ballDirection = 180 - ballDirection;
end
end
end
MoveObject( hBall, ballSpeed, ballDirection );
end
function UpdateRightPaddle()
speed = 5;
pos = get( hRightPaddle, 'position' );
rightY = pos(1,2);
if( rightY + 5 < targetY - 50 && rightY < 400 - 50 )
MoveObject( hRightPaddle, speed, 90 )
elseif( rightY - 5 > targetY - 50 && rightY > 50 )
MoveObject( hRightPaddle, speed, 270 )
end
pos = get( hRightPaddle, 'position' );
rightY = pos( 1,2);
if( rightY > 400 - 50 )
rightY = 350;
elseif( rightY < 50 )
rightY = 50;
end
if( strcmp( get( t, 'Running' ), 'off' ) )
start(t)
end
end
function UpdateRightPaddleAI( ob, data )
% calculate where the ball will colide.
tempBallDirection = NormalizeAngle( ballDirection );
if( tempBallDirection < 90 || tempBallDirection > 270 && ballSpeed > 0 )
ballPos = get( hBall, 'position' );
set( hTempBall, 'position', ballPos );
ballX = ballPos(1,1);
while( ballX < 650 - 10 )
ballPos = get( hTempBall, 'position' );
ballX = ballPos(1,1);
ballY = ballPos(1,2);
MoveObject( hTempBall, 20, tempBallDirection )
% check for temp ball collision with walls.
if ( ballY > 450 - 10 )
if ( tempBallDirection > 0 )
if ( tempBallDirection < 180 )
tempBallDirection = 360 - tempBallDirection;
end
end
elseif ( ballY < 60 )
if( tempBallDirection > 180 )
if( tempBallDirection < 360 )
tempBallDirection = 360 - tempBallDirection;
end
end
end
% line( 0, 0, 'marker', '*', 'parent', hTempBall )
% pause( 0.0005 )
end
pos = get( hTempBall, 'position' );
ballY = pos(1,2);
targetY = ballY + ( rand * 150 ) - 75;
end
end
function UpdateLeftPaddle()
scr = get( hMainWindow, 'position' );
screenX = scr(1,1);
screenY = scr(1,2);
screenH = scr(1,4);
mouse = get(0, 'PointerLocation' );
y = mouse(1,2) - screenY;
if( y > 100 && y < 400 )
paddlePos = get( hLeftPaddle, 'position' );
paddlePos(1,2) = y - 50;
set( hLeftPaddle, 'position', paddlePos );
elseif( y > 400 )
paddlePos = get( hLeftPaddle, 'position' );
paddlePos(1,2) = 400 - 50;
set( hLeftPaddle, 'position', paddlePos );
elseif( y < 100 )
paddlePos = get( hLeftPaddle, 'position' );
paddlePos(1,2) = 100 - 50;
set( hLeftPaddle, 'position', paddlePos );
end
end
function CheckForScore()
pos = get( hBall, 'position' );
xpos = pos(1,1);
ypos = pos(1,2);
if ( xpos < 5 )
set( hBallImage, 'visible', 'off' )
rightScore = rightScore + 1;
set ( hRightScoreText, 'string', num2str( rightScore ) )
pause( .5 )
ResetBall()
elseif ( xpos + 10 > 695 )
set( hBallImage, 'visible', 'off' )
leftScore = leftScore + 1;
set ( hLeftScoreText, 'string', num2str( leftScore ) )
pause( .5 )
ResetBall()
end
end
function ResetBall
pos = get( hBall, 'position' );
pos(1,1) = 345;
pos(1,2) = 255 + floor( rand*100 ) - 50;
set( hBall, 'position', pos )
ballSpeed = 4;
ballDirection = ( (rand(1) < 0.5) * 180 ) ... % 0 or 180
+ ( 45 + (rand(1) < 0.5) * -90 ) ... % + 45 or - 45
+ ( floor( rand * 40 ) - 20 ); % + -20 to 20
set( hBallImage, 'visible', 'on' )
pause(1)
end
function MoveObject( hInstance, speed, direction )
p = get( hInstance, 'position' );
x = p( 1, 1 );
y = p( 1, 2 );
x = x + cosd( direction ) * speed;
y = y + sind( direction ) * speed;
p( 1, 1 ) = x;
p( 1, 2 ) = y;
set( hInstance, 'position', p )
end
function SetObjectPosition( hObject, x, y )
pos = get( hObject, 'position' );
pos(1,1) = x;
pos(1,2) = y;
set( hObject, 'position', pos )
end
function a = NormalizeAngle( angle )
while angle > 360
angle = angle - 360;
end
while angle < 0
angle = angle + 360;
end
a = angle;
end
function QuitButton_CallBack( hObject, eventData )
playing = false;
end
function StartButton_CallBack( hObject, eventData )
set( hObject, 'visible', 'off' );
set( hLeftPaddleImage, 'visible', 'on' )
set( hRightPaddleImage, 'visible', 'on' )
ResetBall();
end
endPassive direction finding
clc
clear all
close all
fs=20e7;
T=1/fs;
t=0:T:0.0000002;
f=10e6;
scanagle_deg=60;
step_deg=6;
theta=-deg2rad(scanagle_deg):deg2rad(step_deg):deg2rad(scanagle_deg);
for i=1:length(theta);
ant1=2*sin(2*pi*f*t);
ant2=2*sin(2*pi*f*t+theta(i));
[my,mx]=max(ant1);
sum_ant(i)=ant1(mx)+ant2(mx);
diff_ant(i)=ant1(mx)-ant2(mx);
ratio_ant(i)=diff_ant(i)/sum_ant(i);
% if diff_ant(i)==0
% diff_ant(i)=0.1;
% end
% ratio1_ant(i)=sum_ant(i)/diff_ant(i);
end
% subplot(311)
% plot(t,ant1,t,ant2)
subplot(211)
plot(rad2deg(theta),sum_ant,rad2deg(theta),diff_ant)
subplot(212)
plot(rad2deg(theta),ratio_ant)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sim_ant1=2*sin(2*pi*f*t);
sim_ant2=2*sin(2*pi*f*t+deg2rad(30));
[smy,smx]=max(sim_ant1);
%%%%also take for same sample value of data
sim_sum_ant=sim_ant1(mx)+sim_ant2(mx);
sim_diff_ant=sim_ant1(mx)-sim_ant2(mx);
sim_ratio_ant=sim_diff_ant/sim_sum_antpassive Sum difference method for finding bearing
clc
clear all
close all
fs=20e7;
T=1/fs;
t=0:T:0.0000002;
f=10e6;
scanagle_deg=60; % Range covered by seeker antenna
step_deg=6;
% for ploting original arrays of sum, diff and ratio
theta=-deg2rad(scanagle_deg):deg2rad(step_deg):deg2rad(scanagle_deg);
for i=1:length(theta);
ant1=1*sin(2*pi*f*t); %Antenna 1
ant2=1*sin(2*pi*f*t+theta(i)); %Antenna 2
[my,mx]=max(ant1);
sum_ant(i)=ant1(mx)+ant2(mx); %Sum of antennas
diff_ant(i)=ant1(mx)-ant2(mx); %diff of antennas
ratio_ant(i)=diff_ant(i)/sum_ant(i); %ratio
end
% subplot(311)
% plot(t,ant1,t,ant2)
% subplot(211)
% plot(rad2deg(theta),sum_ant,rad2deg(theta),diff_ant)
% subplot(212)
% plot(rad2deg(theta),ratio_ant)
%
% figure
% subplot(211)
% plot(rad2deg(theta),sumn_ant,rad2deg(theta),diffn_ant)
% subplot(212)
% plot(rad2deg(theta),ration_ant)
%%%%%%%%%%%%%%%%Recieved signal at antenna for DOA%%%%%%%%%%%%%%%%%%%%%%%%%%
A_ant1=2; % Amplitude of antenna 1
A_ant2=3; % Amplitude of antenna 2
DOA_angle_target=20; % DOA of TARGET
sim_ant11=A_ant1*sin(2*pi*f*t); % Simulated antenna 1
sim_ant22=A_ant2*sin(2*pi*f*t+deg2rad(DOA_angle_target)); % Simulated antenna 2
sim_ant1=sim_ant11/max(sim_ant11); %normalization
sim_ant2=sim_ant22/max(sim_ant22);
[smy,smx]=max(sim_ant1);
%%%%also take for same sample value of data
sim_sum_ant=sim_ant1(smx)+sim_ant2(smx);
sim_diff_ant=sim_ant1(smx)-sim_ant2(smx);
sim_ratio_ant=sim_diff_ant/sim_sum_ant;
%%%%%%%%%%%%% Polynomial fitting of ratio_ant of 6th order%%%%%%%%%%%%
% Error in DOA is obtained because of this
% if polynomial fitting is removed or more accurate results are obtained
% DOA of target can be found with greater accuracy
% Polynomial was obtained though curve fitting toolbox
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p1 = 1.047e-008;
p2 = -6.907e-007;
p3 = 2.383e-005;
p4 = -0.0004914;
p5 = 0.008555;
p6 = -0.09626;
p7 = 0.4215;
x=0;
for ii=1:2200
x=x+0.01;
fitted_model_rat_ant(ii) = p1*x^6 + p2*x^5 + p3*x^4 + p4*x^3 + p5*x^2 + p6*x + p7;
end
theta_new=-scanagle_deg:.0545:scanagle_deg; % Theta for ploting fitted model
figure
plot(theta_new(1:2200),fitted_model_rat_ant)
c1=ceil(sim_ratio_ant*7000); % For comparison of sim_ratio ant and model
c2=ceil(fitted_model_rat_ant*7000); % Different threshold Threshold can be chosen
[r,c,v]= find(c2==c1);
detected_theta=(c.*0.0545)-60 %theta from curve fitting model
if(A_ant1>A_ant2) % condition for checking which angle was correct
correct_theta=detected_theta(1)
elseif(A_ant1<A_ant2)
correct_theta=detected_theta(2)
else
correct_theta=detected_theta
endCorrelation on DSP KIT TMS320C6713 Simulator
#include <stdio.h>
#include <math.h>
double pi=3.14159;
float x[50],y[50];
float r[100];
void correlation(float *x,float *y, int nx, int ny);
int main()
{
int ii;
for(ii=0;ii<50 ;ii++)
{
x[ii]=sin(2.0*pi*ii*3/50);
y[ii]=sin(2.0*pi*ii*3/50);
}
correlation(x,y,50,50);
printf("Complete.\n");
return 0;
}
void correlation(float *x,float *y, int nx, int ny)
{
int n=50,delay=0,maxdelay=50;
int i,j;
double mx,my,sx,sy,sxy,denom;
/* Calculate the mean of the two series x[], y[] */
mx = 0;
my = 0;
for (i=0;i<n;i++)
{
mx += x[i];
my += y[i];
}
mx /= n;
my /= n;
/* Calculate the denominator */
sx = 0;
sy = 0;
for (i=0;i<n;i++)
{
sx += (x[i] - mx) * (x[i] - mx);
sy += (y[i] - my) * (y[i] - my);
}
denom = sqrt(sx*sy);
/* Calculate the correlation series */
for (delay=-maxdelay;delay<maxdelay;delay++)
{
sxy = 0;
for (i=0;i<n;i++)
{
j = i + delay;
if (j < 0 || j >= n)
continue;
else
sxy += (x[i] - mx) * (y[j] - my);
// Or should it be (?)
/* if (j < 0 || j >= n)
sxy += (x[i] - mx) * (-my);
else
sxy += (x[i] - mx) * (y[j] - my);*/
}
r[delay+maxdelay]= ( sxy / denom);





