%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Program for å lese inn pulser fra fotodiode og måle perioden til signalet
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% Initialiser %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
edgeskip = 0; % 1 for å hoppe over annen hver kant for pendelen (Tid og frekvens), 0 for Masse og kraft
duration = 20; % antall sekunder vi skal måle
samplerate=25e3;  % vil lese inn data med 25kHz
channel=1; % Antall kanaler på dataloggeren, starter fra 0
inputrange=10; % innspenning mellom -10 og 10 volt
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if edgeskip == 1
    disp('Satt opp for Tid og frekvens')
elseif edgeskip == 0
    disp('Satt opp for Masse og kraft')
 else
   disp('Velg edgeskip = 0 for Tid og frekvens, 1 for Masse og kraft')  
   return
end

%Create a session
disp('Init DAQ session...')
[DS,devicename]=initDaqSession(duration,samplerate,0);
%Initialize the analog input
disp('Init AD channel...')
[AIch]=initADchannel(DS,devicename,1,'SingleEnded',inputrange);
global data time risingEdge periods meanperiod stdofmeanperiod
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Gjør målingene nå
disp('DAQ starter...')
[data time] = startForeground(DS);
%%%% Analyser data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Finn rising edge (der verdiene stiger) ved å sammenligne hvert datapunkt
% med det etterfølgende datapunktet
threshold = 3.5; %Sett spenningen der passering noteres
risingEdge = find(data(1:end-1) < threshold & data(2:end) > threshold);
% Finn perioden til signalet
periods=diff(time(risingEdge(1:1+edgeskip:end))); %finn tid mellom annenhver risingEdge
meanperiod=mean(periods);
stdofmeanperiod=std(periods)/sqrt(length(periods));
fprintf('Mean period = %.5f +- %.5f s with N = %d periods\n',meanperiod,stdofmeanperiod,length(periods));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% Plott data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(1),plot(time, data), hold on
plot(time(risingEdge(1:end)),threshold*ones(1,...
    length(risingEdge(1:end))),'o')
plot(time(risingEdge(1:1+edgeskip:end)),threshold*ones(1,...
    length(risingEdge(1:1+edgeskip:end))),'k.','MarkerSize',10)
hold off
xlabel('tid (s)'),ylabel('spenning (V)')
figure(2), plot(time(risingEdge(1:1+edgeskip:end-(1+edgeskip))),periods,'*')
xlabel('tid (s)'),ylabel('periode (s)')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%% Lagre data (alt!!) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
filename = input('Hvilket filnavn vil du bruke for å lagre dataene?','s');
%save(filename,'data','risingEdge','periods','meanperiod','stdofmeanperiod')
clear DS
clear AI
save(filename)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
