How to create a delay for a serial connection?
12 views (last 30 days)
Show older comments
I created a GUI to connect to a device, however, now the device collects data before it lights up, which makes the data pointless. Can you please help figure out how to establish a 10 msec delay in the device reading? You can find the code below. The most relevant part of the code starts on line 350.
function varargout = FlexSystemGUInew(varargin)
% FLEXSYSTEMGUINEW MATLAB code for FlexSystemGUInew.fig
% FLEXSYSTEMGUINEW, by itself, creates a new FLEXSYSTEMGUINEW or raises the existing
% singleton*.
%
% H = FLEXSYSTEMGUINEW returns the handle to a new FLEXSYSTEMGUINEW or the handle to
% the existing singleton*.
%
% FLEXSYSTEMGUINEW('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in FLEXSYSTEMGUINEW.M with the given input arguments.
%
% FLEXSYSTEMGUINEW('Property','Value',...) creates a new FLEXSYSTEMGUINEW or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before FlexSystemGUInew_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to FlexSystemGUInew_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 FlexSystemGUInew
% Last Modified by GUIDE v2.5 29-Oct-2021 12:21:42
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @FlexSystemGUInew_OpeningFcn, ...
'gui_OutputFcn', @FlexSystemGUInew_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 FlexSystemGUInew is made visible.
function FlexSystemGUInew_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 FlexSystemGUInew (see VARARGIN)
% Choose default command line output for FlexSystemGUInew
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes FlexSystemGUInew wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% Load graph
axes(handles.detectorPlot)
title('Detector 1')
delete(instrfind)
%% Serial Connection Settings
serialPorts=instrhwinfo('serial');
handles.nPorts=length(serialPorts.SerialPorts);
handles.serPorts = serialPorts.SerialPorts;
% Update handles structure
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = FlexSystemGUInew_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 Auto.
function pushbutton_auto_Callback(hObject, eventdata, handles)
% hObject handle to Auto (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%% Detector info
handles.d_num = get(handles.edit_detectors,'String');
%% Source info
handles.s_num = get(handles.edit_sources,'String');
handles.patch_num=get(handles.edit_patch,'String');
%% Wavelength info
handles.wls = split(get(handles.edit_wavelengths,'String'));
handles.wls_num = length(handles.edit_wavelengths);
set(handles.pushbutton_start,'Enable','on')
guidata(hObject, handles);
% --- Executes on button press in pushbutton_SystemEnable.
function pushbutton_SystemEnable_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_SystemEnable (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
connection = 'Serial';
if strcmp(get(hObject,'String'),'System Disable') % currently disconnected
if strcmp(connection,'Serial') == 1
serConn=serial(handles.serPorts{3}); %'COM4'
set(serConn,'TimeOut', 3);
set(serConn,'BaudRate',115200)
set(serConn,'DataBits',8)
set(serConn,'Parity','none')
set(serConn,'FlowControl','none')
set(serConn,'Terminator','LF');
set(serConn,'StopBits',1);
end
try
%Open selected serial port, enable button functions
fopen(serConn);
handles.serConn=serConn;
%Send mode commands
configStr=':I:0';
fprintf(handles.serConn,'%s',configStr);
pause(1);
receiveText = fgets(handles.serConn);
set(handles.text_IncomingText,'String',receiveText)
set(handles.pushbutton_auto,'Enable','on')
set(handles.pushbutton_save,'Enable','on')
set(handles.pushbutton_SendIntensity,'Enable','on')
set(hObject,'String','System Enable')
handles.filePath = 0;
catch e
errordlg(e.message);
end
else % Disconnect after connecting
set(hObject,'String','System Disable')
set(handles.pushbutton_start,'Enable','off')
set(handles.pushbutton_auto,'Enable','off')
set(handles.pushbutton_save,'Enable','off')
set(handles.pushbutton_saveGraph,'Enable','off')
set(handles.pushbutton_SendIntensity,'Enable','off')
set(handles.text_IncomingText,'String','')
fclose(handles.serConn);
fclose(instrfind);
instrreset;
end
guidata(hObject, handles);
function Background_CloseRequestFcn(hObject, eventdata, handles)
if strcmp(get(handles.pushbutton_SystemEnable,'String'),'SystemDisable') % currently connected
fclose(handles.serConn);
fclose(instrfind);
instrreset;
end
delete(hObject);
pushbutton_start_Callback(hObject, eventdata, handles)
pushbutton_saveGraph_Callback(hObject,eventdata,handles)
function edit_detectors_Callback(hObject, eventdata, handles)
% hObject handle to edit_detectors (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 edit_detectors as text
% str2double(get(hObject,'String')) returns contents of edit_detectors as a double
% --- Executes during object creation, after setting all properties.
function edit_detectors_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_detectors (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 edit_sources_Callback(hObject, eventdata, handles)
% hObject handle to edit_sources (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 edit_sources as text
% str2double(get(hObject,'String')) returns contents of edit_sources as a double
% --- Executes during object creation, after setting all properties.
function edit_sources_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_sources (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 edit_patch_Callback(hObject, eventdata, handles)
% hObject handle to edit_patch (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 edit_patch as text
% str2double(get(hObject,'String')) returns contents of edit_patch as a double
% --- Executes during object creation, after setting all properties.
function edit_patch_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_patch (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 edit_wavelengths_Callback(hObject, eventdata, handles)
% hObject handle to edit_wavelengths (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 edit_wavelengths as text
% str2double(get(hObject,'String')) returns contents of edit_wavelengths as a double
% --- Executes during object creation, after setting all properties.
function edit_wavelengths_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_wavelengths (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 edit_gain_Callback(hObject, eventdata, handles)
% hObject handle to edit_gain (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 edit_gain as text
% str2double(get(hObject,'String')) returns contents of edit_gain as a double
% --- Executes during object creation, after setting all properties.
function edit_gain_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_gain (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 edit_repeat_Callback(hObject, eventdata, handles)
% hObject handle to edit_repeat (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 edit_repeat as text
% str2double(get(hObject,'String')) returns contents of edit_repeat as a double
% --- Executes during object creation, after setting all properties.
function edit_repeat_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_repeat (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
% --- Executes on button press in pushbutton_start.
function pushbutton_start_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Clear graphs
cla(handles.detectorPlot)
% Set graph titles
axes(handles.detectorPlot)
title('Detector 1')
handles.current_val = 0;
set(handles.pushbutton_stop,'UserData',false)
% Get variables
repeat_number = str2num(get(handles.edit_repeat,'String'));
% Initialize
allData = zeros(repeat_number,8); %8 for 2 patches
data = zeros(1,repeat_number*8); %8 for 2 patches
count = 0;
time = 0;
tic;
t1 = 0;
t2 = 0;
d = str2num(handles.d_num);
s = str2num(handles.s_num);
patch_num=str2num(handles.patch_num);
pds = zeros(patch_num,d);
srcs = zeros(patch_num,d);
detectorNames = strings(1,d);
for x = 1:d
detectorNames(x) = sprintf('Detector %d',x);
end
% Collecting data from serial port
for i = 1:repeat_number
set(handles.time,'String',num2str(i))
if get(handles.pushbutton_stop,'UserData') == true
break;
end
% Send and receive data
configStr=':I:0';
fprintf(handles.serConn,'%s',configStr);
pause(.05)
receiveText = fgets(handles.serConn);
% set(handles.receivingText,'String',receiveText)
while isempty(str2num(receiveText)) % Ignoring any serial text
set(handles.receivingText,'String',receiveText)
receiveText = fgets(handles.serConn);
end
% for index=1:3
% pause(0.5)
% receiveText = fgets(handles.serConn)
% end
% Storing the serial data
data = str2num(receiveText);
allData(i,:) = data;
detectors = reshape(data,[patch_num,d]); % Sorting data by detector #
if i == 1
pds = reshape(data, [d,patch_num]);
% for j = 1:patch_num
% srcs(j,:) = detectors(:,j);
% end
% srcs2 = srcs;
end
% Adding to each detector data vector
if i > 1
pds = [pds, reshape(data, [d,patch_num])];
% for k = 1:patch_num
% srcs(k,:) = detectors(:,k);
% end
% srcs2 = [srcs2, srcs];
end
len = length(pds(1,:)); % length of each vector = i*6
handles.length = len;
handles.frames = repeat_number;
% Plot Detectors
% det_number = get(handles.popupmenu_graphDetectors,'Value');
% axes(handles.detectorPlot)
% cla
% for j = 1:handles.wls_num
% plot(pds(d*(j-1)+det_number,:))
% hold on
% xlim([0 len])
% title(sprintf('Detector %d',det_number))
% xticks(0:100:d*repeat_number)
% xtickangle(45)
% x = pds(d*(j-1)+det_number,:);
% text(len,x(end),sprintf('WL%d',j))
% end
% Store data
handles.PDS = pds;
% handles.sources = srcs2;
if ~isempty(receiveText)
if count ~= 0
t1 = time(count);
end
count = count+1;
time(count) = toc;
t2 = time(count);
end
end
handles.data = allData;
set(handles.pushbutton_save,'String','Browse')
set(handles.pushbutton_save,'Enable','on');
set(handles.edit_saveFile,'String','')
% If name fields are empty -> choose dir to save
while handles.filePath == 0
directory = uigetdir;
handles.filePath = directory;
end
% Auto save data to folder name
file = uiputfile(sprintf('%s\\*.txt;*.*',handles.filePath));
if ~isequal(file,0)
try
name = sprintf('%s\\%s',handles.filePath,file);
set(handles.edit_saveFile,'String',name);
dlmwrite(name,allData,'Delimiter','\t','newline','pc')
set(handles.pushbutton_save,'String','Saved');
set(handles.pushbutton_save,'Enable','off');
catch
set(handles.pushbutton_save,'String','Invalid file name')
end
end
set(handles.pushbutton_saveGraph,'Enable','On')
guidata(hObject,handles);
function pushbutton_start_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_intensityR (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 edit_intensityR_Callback(hObject, eventdata, handles)
% hObject handle to edit_intensityR (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 edit_intensityR as text
% str2double(get(hObject,'String')) returns contents of edit_intensityR as a double
% --- Executes during object creation, after setting all properties.
function edit_intensityR_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_intensityR (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 edit_intensityG_Callback(hObject, eventdata, handles)
% hObject handle to edit_intensityG (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 edit_intensityG as text
% str2double(get(hObject,'String')) returns contents of edit_intensityG as a double
% --- Executes during object creation, after setting all properties.
function edit_intensityG_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_intensityG (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 edit_intensityB_Callback(hObject, eventdata, handles)
% hObject handle to edit_intensityB (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 edit_intensityB as text
% str2double(get(hObject,'String')) returns contents of edit_intensityB as a double
% --- Executes during object creation, after setting all properties.
function edit_intensityB_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_intensityB (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
% --- Executes on button press in pushbutton_SendIntensity.
function pushbutton_SendIntensity_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_SendIntensity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
int_R = get(handles.edit_intensityR,'String');
int_G = get(handles.edit_intensityG,'String');
int_B = get(handles.edit_intensityB,'String');
configStr = sprintf(':$:%s:%s:%s',int_R,int_G,int_B);
fprintf(handles.serConn,'%s',configStr);
pause(0.5)
receiveText = fgets(handles.serConn);
set(handles.receivingText,'String',receiveText)
% --- Executes during object creation, after setting all properties.
function pushbutton_sendIntensity_CreateFcn(hObject, eventdata, handles)
% hObject handle to Sources (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 frequency_axes_Createfcn(varargin)
function edit_saveFile_Callback(hObject, eventdata, handles)
% hObject handle to edit_saveFile (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 edit_saveFile as text
% str2double(get(hObject,'String')) returns contents of edit_saveFile as a double
% --- Executes during object creation, after setting all properties.
function edit_saveFile_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_saveFile (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
% --- Executes on button press in pushbutton_save.
function pushbutton_save_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_save (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% If no current file path, create one
if isempty(handles.filePath)
date = datestr(now,'dd-mmm-yyyy');
directory = uigetdir;
handles.filePath = fullfile(directory,date);
end
file = uiputfile(sprintf('%s/*.txt',handles.filePath));
if ~isequal(file,0)
try
name = sprintf('%s/%s',handles.filePath,file);
set(handles.edit_saveFile,'String',name);
name = get(handles.edit_saveFile,'String');
allData = handles.data;
dlmwrite(name,allData,'Delimiter','\t','newline','pc')
set(handles.pushbutton_save,'String','Saved');
set(handles.pushbutton_save,'Enable','off');
catch
set(handles.edit_saveFile,'String','Invalid file name')
end
end
% --- Executes on button press in pushbutton_saveGraph.
function pushbutton_saveGraph_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_saveGraph (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 pushbutton_stop.
function pushbutton_stop_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_stop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
1 Comment
Tobias Held
on 6 Jan 2022
The Matlab Forum is not here to code for you...
Specify the question/ give a minimal example and look into this:
https://ch.mathworks.com/help/matlab/matlab_prog/use-a-matlab-timer-object.html
https://ch.mathworks.com/help/matlab/ref/timer.wait.html?searchHighlight=wait&s_tid=srchtitle_wait_1
Answers (1)
KALASH
on 8 Apr 2024
Hi Karim,
I understand you want to create a 10msec delay before your device starts collecting data.
For that you can use the MATLAB’s “timer” function in your code as shown below:
% Create a timer object
delayTimer = timer('ExecutionMode', 'singleShot', 'StartDelay', 0.01);
% Collecting data from serial port
for i = 1:repeat_number
set(handles.time,'String',num2str(i))
if get(handles.pushbutton_stop,'UserData') == true
break;
end
% Start the timer
start(delayTimer);
% Wait for the timer to finish
wait(delayTimer);
% Send and receive data
configStr=':I:0';
fprintf(handles.serConn,'%s',configStr);
receiveText = fgets(handles.serConn);
% Rest of your data collection code continues...
end
You may refer to the below documentation for more information on “timer” function:
Alternatively, if that doesn’t work you can try using tic toc as below:
% Create a 10-millisecond delay
tic;
while toc < 0.01
% don’t do anything
end
For more information on tic toc refer to the below documentation:
Hope this helps!
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!