MATLAB: How to count how many times a button was pressed

buttonguipress

I want to write a code where I can check how many times a button was pressed (keyboard, mouse or even a pointer).
The code I have now is not working the way I want. As I click on a button for more than 1 second, it gives me a counting of 10 or more times. I want my code to count the number of clicks someone does on a button despite they spent 1second or 5seconds with the finger pressed against the button. Here is my function:
function youPressedSpaceBrah
set(figure,'KeyPressFcn',@youPressedSomething,'Name','Multitasking Game - Alerta Visual Nivel 1','NumberTitle','off', 'MenuBar', 'none','ToolBar', 'none');
clf;
%State variables
count = 0;
allowCounting = true;
%Callback functions
%When the user presses a key
function youPressedSomething(~,eventdata)
if strcmp(eventdata.Character,' ')
if allowCounting
count = count+1
end
end
end
end
Here is the code to call my function to the main code:
function youPressedSomething(~,eventdata)
erros=erros+1;
end
Thanks for your support!

Best Answer

Joana,
If I understand your question correctly, you want to consider 'Press and Hold' of any key as a single key press. But usually press and hold of a key is considered as multiple quick key press-releases of the same key. So as you can see in the below code I've used a simple tic-toc combination to check if the time between a key press-release of the same key is less than 0.05s(you can tune this time if you want), in which case I'm just printing the key count value at that point without any increment.
function KeyPressAnalyze
KeyPress_Main = figure;
set(KeyPress_Main, 'KeyPressFcn',@KeyPress_Main_KeyPress_Callback, 'KeyReleaseFcn',@KeyPress_Main_KeyRelease_Callback);
KeyPressCount = 0;
PressedKeyCurrent = {};
function KeyPress_Main_KeyPress_Callback(Handle, Event)
tic;
PressedKeyCurrent = Event.Key;
end
function KeyPress_Main_KeyRelease_Callback(Handle, Event)
KeyReleaseTime = toc;
disp(KeyReleaseTime);
ReleasedKey = Event.Key;
if (strcmp(PressedKeyCurrent, ReleasedKey) && (KeyReleaseTime < 0.05))
disp(KeyPressCount);
else
KeyPressCount = KeyPressCount + 1;
disp(KeyPressCount);
end
end
end
Please let me know if this fixed your issue.
Regards
PG