%  SerialComm.m  Scott McLeod, Sandeep Prabhu, Brett Pihl 2/4/2008
%  This program is designed to communicate to a PIC 18F4520 via RS232 (Serial) Communication.
%  
%  The main loop of this program waits for a character input from the user,
%  upon which it transmits the ascii value and waits for data to be written.
%clear
clc
delete(instrfind)

s = serial('COM5','BAUD',19200);           % Create serial object (PORT Dependent)
fopen(s)                                    % Open the serial port for r/w

prompt = 'Recording Data'; 


%acc = zeros(100, 26);

for freq = 5:95
    fprintf('Frequency: %i\n', freq)
    for i = 1:30
        in = fscanf(s);                          % Read Data back from PIC
        %fprintf(in);
        comma = find(in == ',');
        first_num = in(1:comma);
        second_num = in(comma+1:end);
        acc(freq,str2double(first_num)+1) = str2double(second_num);
    end
end

%Convert data to G's
scale = 2;
acc = acc ./ (2^10-1);           %normalize from 0 to 1
acc = acc - 0.5;                 %subtract to center at 0
acc = acc * 2 * scale;    %multiply by scaling Mode

%super_cetner
for i=1:96
    acc(i, :) = acc(i, :) - sum(acc(i, :))/numel(acc(i,:));
    vpp(i) = max(acc(i,:)) - min(acc(i,:));
end

plot(1:numel(vpp), vpp, 'o');

vpp_db = 20*log10(vpp);
semilogx(1:numel(vpp), vpp_db);



%freq = 10;
%plot(1:29, acc(freq, :));

fclose(s);                                  % Close the serial port
delete(s);                                  % And Destory the PORT