% This example uses the xippmex('cont') command to retrieve continuous
% data from the Ripple Grapevine processor and compute the sliding window
% power spectral density spectrograms.
% Clean the world
close all; fclose('all'); clc; clear all;
% Initialize xippmex
status = xippmex;
if status ~= 1; error('Xippmex Did Not Initialize'); end
% Stream Setup
FR = 30; % Hz, plot update framerate
display_s = 5; % seconds, length of display window (0-5 seconds)
pause(display_s); % pause for display duration to fill signal buffer
stream_ch = 1; % channel number, 1 denotes A-1
stream = 'raw';
switch(stream)
case 'raw'
Fs = 3e4; % Hz, sampling frequency of signal
case 'lfp'
Fs = 1e3; % Hz, sampling frequency of signal
case 'hi-res'
Fs = 2e3; % Hz, sampling frequency of signal
case 'hifreq'
Fs = 7.5e3; % Hz, sampling frequency of signal
otherwise
error('%s is an invalid stream type.\n', stream);
end
if xippmex('signal', stream_ch, stream) == 0
xippmex('signal', stream_ch, stream, 1);
end
% FFT Setup
window_ms = 512; % FFT window size in ms
window_samp = floor(window_ms*Fs/1e3); % FFT window size in samples
N = 2^nextpow2(floor(window_samp/2)); % Size of PSD
f_range = [0 75]; % Hz, spectrogram display range
n_sig = Fs/1e3 * round(display_s*1e3);
n_psd = round(display_s*FR);
t_sig = linspace(-display_s,0,n_sig); % Time for Signal
t_psd = linspace(-display_s,0,n_psd); % Time for Spectrogram
f_psd_total = linspace(0,Fs,2*N); % Frequency for Spectrogram
f_ind = find(f_psd_total >= f_range(1)...
& f_psd_total <= f_range(2) );
f_psd = f_psd_total(f_ind); % Frequency for Spectrogram display
x_sig = zeros(n_sig,1); % Signal Buffer
x_psd = zeros(length(f_psd),n_psd); % Spectrogram Buffer
% Plot Setup
psd_plot = figure;
subplot(211);
h_sig = plot(t_sig,x_sig,'b'); % signal plot
x_range = t_sig([1 end]); % seconds, display range
xlim(x_range);
title(sprintf('Channel #%d, %s',stream_ch,stream)); xlabel('Time (s)'); ylabel('\muV');
subplot(212);
h_psd = imagesc(t_psd,f_psd,x_psd); % spectrogram plot
set(gca,'ydir','normal','ylim',f_range);
title('Spectrogram'); xlabel('Time (s)'); ylabel('Frequency (Hz)');
% Main Collection/Update Loop while figure is open
t0 = xippmex('time');
while isa(psd_plot,'handle') && isvalid(psd_plot)
t1 = xippmex('time');
if (t1-t0)>=(3e4/FR)
% Collection
[x_sig,ts] = xippmex('cont',stream_ch,round(display_s*1e3),stream);
% Calculation
sig_sample = x_sig(end-window_samp+1:end);
psd_sample = 2*abs(fft(sig_sample,2*N));
x_psd(:,1:end-1) = x_psd(:,2:end);
x_psd(:,end) = (psd_sample(f_ind))';
% Plot
set(h_sig,'ydata',x_sig);
set(h_psd,'cdata',(x_psd));
drawnow;
t0 = t1;
end
end
disp('Exiting main loop');
% Close xippmex after exiting loop
disp('Closing xippmex connection');
xippmex('close');