How to draw real time plot in guide matlab
1 view (last 30 days)
Show older comments
Hello, I am taking a single input from a National Instrument NI USB 6008 DAQ. Right now I have a GUI where i can plot. I was looking for a way to plot in real time. I tried few options however they plot in a seperate windows not within the gui. Thanks!!
function varargout = ptdaq(varargin)
% PTDAQ MATLAB code for ptdaq.fig
% PTDAQ, by itself, creates a new PTDAQ or raises the existing
% singleton*.
%
% H = PTDAQ returns the handle to a new PTDAQ or the handle to
% the existing singleton*.
%
% PTDAQ('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in PTDAQ.M with the given input arguments.
%
% PTDAQ('Property','Value',...) creates a new PTDAQ or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ptdaq_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ptdaq_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help ptdaq
% Last Modified by GUIDE v2.5 01-Feb-2018 16:15:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @ptdaq_OpeningFcn, ...
'gui_OutputFcn', @ptdaq_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before ptdaq is made visible.
function ptdaq_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to ptdaq (see VARARGIN)
% Choose default command line output for ptdaq
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
set(get(handles.timehist_axes,'xlabel'),'string','Time (sec)');
set(get(handles.timehist_axes,'ylabel'),'string','\DeltaP (Inches Water)');
grid(handles.timehist_axes)
% UIWAIT makes ptdaq wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = ptdaq_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in acquire_btn.
function acquire_btn_Callback(hObject, eventdata, handles)
% hObject handle to acquire_btn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Update handles structure
guidata(hObject, handles);
% Turn off DAQ warnings on voltage range (manually set)
warning('off','all')
%% Query Sampling Parameters
% Check validity of input sample rate and process it
samp_rate_val = str2double(get(handles.samp_rate_Hz,'String'));
% Check for a non-empty edit box and a valid number (no letters or symbols).
if isempty(get(handles.samp_rate_Hz,'String')) || isnan(samp_rate_val) || samp_rate_val > 1000 || samp_rate_val < 1
% They didn't enter a number.
% They entered a character, symbols, or something else not allowed.
% Assign some default and notify the user.
default_sample_rate = 1000;
samp_rate_val = default_sample_rate;
message = sprintf('Invalid Sample Rate.\nDefault %.0f Hz used.', default_sample_rate);
uiwait(warndlg(message));
% Put it into the text box too, replacing their bad entry.
handles.samp_rate_Hz.String = num2str(samp_rate_val);
end
% Check validity of input duration and process it
duration_val = str2double(get(handles.samp_duration_sec,'String'));
% Check for a non-empty edit box and a valid number (no letters or symbols).
if isempty(get(handles.samp_duration_sec,'String')) || isnan(duration_val) || duration_val > 30 || duration_val < 0
% They didn't enter a number.
% They entered a character, symbols, or something else not allowed.
% Assign some default and notify the user.
default_duration = 3;
duration_val = default_duration;
message = sprintf('Invalid Recording Duration.\nDefault %.0f sec used.', default_duration);
uiwait(warndlg(message));
% Put it into the text box too, replacing their bad entry.
handles.samp_duration_sec.String = num2str(duration_val);
end
% Check validity of zero offset and process it
volts_offset_val = str2double(get(handles.volts_zero_txt,'String'));
% Check for a non-empty edit box and a valid number (no letters or symbols).
if isempty(get(handles.volts_zero_txt,'String')) || isnan(volts_offset_val) || volts_offset_val > 10 || volts_offset_val < 0
% They didn't enter a number.
% They entered a character, symbols, or something else not allowed.
% Assign some default and notify the user.
default_offset = 5.04;
volts_offset_val = default_offset;
message = sprintf('Invalid Offset Voltage.\nDefault %.0f sec used.', default_offset);
uiwait(warndlg(message));
% Put it into the text box too, replacing their bad entry.
handles.volts_zero_txt.String = num2str(volts_offset_val);
end
%% Update button text for user feedback
set(handles.acquire_btn,'String','Acquiring...');
%% Create a data acquisition session
daqSession = daq.createSession('ni');
%% Add channels specified by subsystem type and device
ch = daqSession.addAnalogInputChannel('Dev1','ai0','Voltage');
% Set terminal cfg to RSE/single-ended (vs. differential)
ch.TerminalConfig = 'SingleEnded';
% Set input range to +/- 10 volts
ch.Range = [-10,10];
%% Configure properties
daqSession.DurationInSeconds = duration_val;
daqSession.Rate = samp_rate_val;
%% Run the data acquisition session
[volts,time] = daqSession.startForeground();
%% Convert volts to engineering units
% Calculate scale factor from transducer limits
prange = 30; % input range (inches of water column)
vrange = 10; % voltage output max limit (VDC)
scale_factor_vdc2inwc = vrange/prange;
volts_zerodp = volts_offset_val;
% Apply scale factor to voltage data
data_iwc = (volts-volts_zerodp)./scale_factor_vdc2inwc;
%% Plot data
plot(handles.timehist_axes, time, data_iwc,'-ob','MarkerSize',2);
ylim(handles.timehist_axes,[-15 15]);
xlim(handles.timehist_axes,[0 duration_val]);
set(get(handles.timehist_axes,'xlabel'),'string','Time (sec)');
set(get(handles.timehist_axes,'ylabel'),'string','\DeltaP (Inches Water)');
grid(handles.timehist_axes)
%% Calculate and display statistics
% Mean
% inches of water
mean_dp_iwc = sprintf('%.2f', mean(data_iwc));
set(handles.mean_dp_inwc_txt, 'String', mean_dp_iwc);
% pascals
mean_dp_pa = str2double(mean_dp_iwc)*248.84;
mean_dp_pa = sprintf('%.2f', mean_dp_pa);
set(handles.mean_dp_pa_txt, 'String', mean_dp_pa);
% Standard Deviation
% inches of water
std_dp_iwc = sprintf('%.2f', std(data_iwc));
set(handles.std_dp_inwc_txt, 'String', std_dp_iwc);
% pascals
std_dp_pa = str2double(std_dp_iwc)*248.84;
std_dp_pa = sprintf('%.2f', std_dp_pa);
set(handles.std_dp_pa_txt, 'String', std_dp_pa);
clear data time
%% Disconnect from the device
daqSession.release();
delete(daqSession);
clear daqSession;
%% Update button text for user feedback
set(handles.acquire_btn,'string','Press to Acquire');
% Update handles structure
guidata(hObject, handles);
% Turn warnings back on
warning('on','all')
function samp_rate_Hz_Callback(hObject, eventdata, handles)
% hObject handle to samp_rate_Hz (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of samp_rate_Hz as text
% str2double(get(hObject,'String')) returns contents of samp_rate_Hz as a double
% --- Executes during object creation, after setting all properties.
function samp_rate_Hz_CreateFcn(hObject, eventdata, handles)
% hObject handle to samp_rate_Hz (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function samp_duration_sec_Callback(hObject, eventdata, handles)
% hObject handle to samp_duration_sec (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of samp_duration_sec as text
% str2double(get(hObject,'String')) returns contents of samp_duration_sec as a double
% --- Executes during object creation, after setting all properties.
function samp_duration_sec_CreateFcn(hObject, eventdata, handles)
% hObject handle to samp_duration_sec (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over acquire_btn.
function acquire_btn_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to acquire_btn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in quit_btn.
function quit_btn_Callback(hObject, eventdata, handles)
% hObject handle to quit_btn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
choice = questdlg('Are you sure you want to quit?', ...
'Quit?', ...
'Yes','No','Yes');
switch choice
case 'Yes'
% Turn off file type selection flags to quit without error
handles.ftypeVals = [0 0];
% Update handles structure
guidata(hObject,handles)
% Close the figure window
close(handles.figure1);
case 'No'
% Return to making selections
end
% --- Executes on closing window.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to profileRadio4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if isequal(get(hObject,'waitstatus'),'waiting')
% The GUI is still in UIWAIT, so use UIRESUME
uiresume(hObject);
else
% The GUI is no longer waiting, just close it
delete(hObject)
end
function volts_zero_txt_Callback(hObject, eventdata, handles)
% hObject handle to volts_zero_txt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of volts_zero_txt as text
% str2double(get(hObject,'String')) returns contents of volts_zero_txt as a double
% --- Executes during object creation, after setting all properties.
function volts_zero_txt_CreateFcn(hObject, eventdata, handles)
% hObject handle to volts_zero_txt (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
3 Comments
Rik
on 13 Jan 2020
You have posted 5 screens worth of code, 287 non-empty lines. Of these lines, at most 170 are remotely relevant. You have posted no indication of where we should be looking for the code you want to change or optimize.
You should make it easy for people to help you. Currently you aren't. One thing I did notice was this code:
%Add Listeners
%Add listeners to session for available data and error events.
lh1 = addlistener(s, 'DataAvailable', @recordData);
lh2 = addlistener(s, 'ErrorOccurred', @(~,eventData) disp(getReport(eventData.Error)));
%Clean Up
%Remove event listeners and clear the session and channels, if any.
delete(lh1)
delete(lh2)
Why are you creating a listener and then immediately delete it? Is this code you copied from somewhere without understanding it? You also use guidata(hObject,handles) in places where it doesn't make sense. I get the distinct feeling GUIDE is holding you back with its confusing and verbose setup.
Answers (1)
See Also
Categories
Find more on Graphics Object Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!