%% Measure the Time Delay Between Two Signals
% You transmit a sinusoidal signal and get back an "echo" from an object. Measuring the time delay between the outgoing and incoming signals may allow you to estimate the distance to the object.
% The data are collected and displayed by an oscilloscope that produces two ASCII data files. Load the files to the workspace. The first column of each file is the time, the second is the signal. Extract the sample rate.

tx = load('tx.txt');
txt = tx(:,1);
txs = tx(:,2);
dt = diff(txt);
Fs = 1/dt(1);

rx = load('rx.txt');
rxt = rx(:,1);
rxs = rx(:,2);

%
% Locate the peaks and troughs of the signals. Use the peak locations to determine the frequency of each signal. Use the peak values to compute the ratio of transmitted to received amplitude.

[txp,txpl] = findpeaks(txs);
[txm,txml] = findpeaks(-txs);

averageTx = (mean(txp)+mean(txm))/2;

Ftx = 1/mean(diff(txt(txpl)))

[rxp,rxpl] = findpeaks(rxs); 
[rxm,rxml] = findpeaks(-rxs);
rxml(end) = [];
rxm(end) = [];

averageRx = (mean(rxp)+mean(rxm))/2;

Frx = 1/mean(diff(rxt(rxpl)))

Ratio = averageTx/averageRx

plot(txt,txs,txt(txpl),txp,'or',txt(txml),-txm,'or', ...
     rxt,rxs,rxt(rxpl),rxp,'om',rxt(rxml),-rxm,'om')
xlabel('Time (s)')
ylabel('Signals (arb.)')
title('Original')

%
% The delay (in samples) of the received signal is the lag at which the cross-correlation attains the maximum positive value.

[xc,lags] = xcorr(txs,rxs);
 
plot(lags,xc)
xlabel('Lags')
ylabel('Cross-correlation')

[maxc,maxi] = max(xc);
lagSamp = lags(maxi)

%
% Line up the signals by delaying rxt by lagSamp. Use the delay to find the time difference.

rlag = rxt(lagSamp:end);
rxsg = rxs(1:end-lagSamp+1);

plot(txt,txs,txt(txpl),txp,'or',txt(txml),-txm,'or', ...
     rlag,rxsg,rlag(rxpl),rxp,'om',rlag(rxml),-rxm,'om')
xlabel('Time (s)')
ylabel('Signals (arb.)')
title('Aligned')

TimeDiff = lagSamp/Fs

% Because the transmitted and received signals are sinusoidal, the obtained time difference is ambiguous. Any integer multiple of TimeDiff is a correct estimate. In applications where such ambiguities arise, pulsed waveforms are preferred.
% Copyright 2015 The MathWorks, Inc.