
% ------------------- Read and Process PCM Data ------------------- % 
% Steps:
% Configure empy_audio_example with DEBUG_PRINT_OUT = 2 to output RAW
% PCM data to UART (PIN DI020).
% Configure Logic Analyzer (Saleae) to read Async Serial (under same
% parameters UART was configured)
%

clearvars;
x = readtable('C:\Users\a0232184\Desktop\C\Document\projects\0000 lprf sw apps\ble\customers\samsung\cc2340_audio\data\pcm_data_sweep3.csv');
x = x(:,"data");
x = table2array(x);
len = size(x);
len = len(1);
pcm_data = 0;
count = 1;

for i = 1:2:len-1

    lsb = dec2hex(x(i));
    msb = dec2hex(x(i+1));
    pcm_word = append(msb,lsb);
    pcm_word_2 = typecast(uint16(hex2dec(pcm_word)),'int16');
    pcm_data(count) = pcm_word_2;
    count = count + 1;
    
end

fprintf('------- PERFORMANCE METRICS -------\n');

%FFT
fft_pcm = fft(pcm_data);
L = size(fft_pcm);
L = L(2);
Fs = 16281;
tiledlayout(3,1)
nexttile
plot(Fs/L*(0:L-1),abs(fft_pcm),"LineWidth",3)
title("Magnitude vs Frequency FFT")
xlabel("Frequency (Hz)")
ylabel("Magnitud")

nexttile
%SNR
snr(pcm_data,Fs,3);
snr_value = snr(pcm_data,Fs,3);
SNR_pcm = sprintf('SNR (dB) --- %s',snr_value);
disp(SNR_pcm);

%PCM Data
nexttile
plot(pcm_data(3000:4000));
title("PCM Data")
xlabel("Sample")
ylabel("Magnitud")

%THD
thd_value = thd(pcm_data,Fs);
thd_value_percentage = 100*10^(thd_value/20);
THD_pcm = sprintf('THD (percentage) --- %s',thd_value_percentage);
disp(THD_pcm)

%RUN ONLY THIS FOR THE FREQUENCY SWEEP! COMMENT OUT THE OTHER METRICS.
%Periodogram power spectral density estimate
figure;
fs = 16281;
% tiledlayout(2,1)
nexttile
pspectrum(pcm_data,fs)
% nexttile
% pspectrum(pcm_data,fs,'spectrogram',TimeResolution=0.2)
