MATLAB: How to count key presses in limited time

guiguide

my task is using a GUI, to count during 10 seconds the times the subject pressed on the spacebar . after building a GUI that gets the subject's id, it makes a text visible that says- " the 10 seconds will start when you press the spacebar for the first time"
now- where in the code (in which function) I have to put the timer and counter orders? and how do I make a counter that works for a limited time of x seconds.
I guess i need to use somehow the keypress and keyrelease functions although I am not too fimiliar with them..

Best Answer

Oh, you need timer objects and a key press function brah! Also, you gotta stop thinking in loops and start thinking in callbacks!
Check out the example below...
Some key points
1. Listen to the figure to see when a key is pressed
figure('KeyPressFcn',@youPressedSomething)
2. Use a timer object with callbacks that control a state variable
t = timer(...)
There's good documentation on both these things brah!
Also I made a typo when typing "spacebar" and changed it to "spacebrah" and thought it was funny so I kept it going in this post (hence me saying "brah" a lot)
Example:
function youPressedSpaceBrah
%Create figure and text box
fh = figure('DeleteFcn',@cleanUpTimer,'KeyPressFcn',@youPressedSomething);
th = uicontrol('Parent',fh,'Style','text','Position',[10 10 300 30],...
'String','You have not hit space yet');
%State variables
count = 0;
allowCounting = false;
%Timer
t = timer('StartDelay',10,'TasksToExecute',1,'StartFcn',@timerStarted,...
'TimerFcn',@timerFinished);
%Callback functions
%When the user presses a key
function youPressedSomething(~,eventdata)
%See if it is the space bar
if strcmp(eventdata.Character,' ')
if allowCounting
count = count+1;
set(th,'String',['You hit space ' num2str(count) ' times brah!']);
else
startTimer;
end
end
end
%Kick off the timer!
function startTimer
start(t);
end
%Callback for when timer starts
function timerStarted(~,~)
count = 0;
allowCounting = true;
end
%Callback for when timer finishes
function timerFinished(~,~)
allowCounting = false;
end
%Cleanup (delete timer object)
function cleanUpTimer(~,~)
stop(t);
delete(t);
end
end