I'm trying to write a script which gets user input for a specified time interval. I wrote a simple script as below:
timeEllapsed=0;
Count=0;
while 1
tic
input('press enter');
timeEllapsed=timeEllapsed+toc;
Count=Count+1;
if(timeEllapsed>5)
break;
end
end
disp ('result is:')
disp(Count)
This script gets user input, when the time between first and last input less than 5 seconds. But this script waits indefinitely if user doesn't enter any input as expected. Is there any way to get user input for exactly given time interval?
Thanks in advance!
This is a self contained solution...
function output = timeinput(t,default_string)
% TIMEINPUT
% Input arguments:
% t - time delay
% default_string - string which is returned if nothing is entered
%
% Examples:
% If a string is expected
% x = timeinput(20,'no input')
% If a number is expected
% x = str2num(timeinput(20,'1'))
%
if nargin == 1
default_string = '';
end
% Creating a figure
h = figure('CloseRequestFcn','','Position',[500 500 200 50],'MenuBar','none',...
'NumberTitle','off','Name','Please insert...');
% Creating an Edit field
hedit = uicontrol('style','edit','Units','pixels','Position',[10 15 180 20],'callback','uiresume','string',default_string);
% Defining a Timer object
T = timer('Name','mm', ...
'TimerFcn','uiresume', ...
'StartDelay',t, ...
'ExecutionMode','singleShot');
% Starting the timer
start(T)
uiwait(h)
% Defining the return value
output = get(hedit,'String');
% Deleting the figure
delete(h)
% Stopping and Deleting the timer
stop(T)
delete(T)
To run a 5 seconds timeout input, just write:
x = timeinput(5,'no input')
https://www.mathworks.com/matlabcentral/answers/95301-how-can-i-implement-a-timer-dependent-input-request-in-matlab
Source : http://www.mathworks.com/matlabcentral/answers/96229-how-can-i-have-a-dialog-box-or-user-prompt-with-a-time-out-period
function varargout = timeoutDlg(dlg, delay, varargin)
% Dialog function with timeout property
% dlg is a handle to the dialog function to be called
% delay is the length of the delay in seconds
% other input arguments as required by the dialog
% EXAMPLE FUNCTION-CALL
% To display an input dialog box (REFER MATLAB HELP DOC) with a
% timeout = 6 second say, the function call would be:
%
% [matrix_size_value, colormap_string] = timeoutdlg(@inputdlg, 6, ...
% {'Enter matrix size:','Enter colormap name:'}, ...
% 'Input for peaks function', 1, {'20','hsv'})
% Setup a timer to close the dialog in a moment
f1 = findall(0, 'Type', 'figures');
t = timer('TimerFcn', {@closeit f1}, 'StartDelay', delay);
start(t);
% Call the dialog
retvals = dlg(varargin{:});
if numel(retvals) == nargout
varargout = retvals(:);
else
varargout = cell(1, nargout);
end
% Delete the timer
if strcmp(t.Running, 'on')
stop(t);
end
delete(t);
function closeit(src, event, f1)
disp('Time out!');
f2 = findall(0, 'Type', 'figure');
fnew = setdiff(f2, f1);
if ishandle(fnew);
close(fnew);
end