如何在Matlab中检测键盘空格键按下情况? [英] How to detect keyboard spacebar press in matlab?
问题描述
我想检测用户在5秒钟内单击空格键的次数
I want to detect how many times the user click spacebar in 5 seconds
是否有解决此问题的好方法?
谢谢
Is there any good way to fix this problem?
Thanks
推荐答案
一种轻松从键盘读取用户输入的方法是创建一个新图形并指定一个KeyPressFcn
回调函数,如果有任何键被按下,该函数将自动执行.按下.
One way to easily read user inputs from the keyboard is to create a new figure and specify a KeyPressFcn
callback function, which is executed automatically if any key is pressed.
让我们从创建一个新人物开始.因为我们不需要该图来显示任何东西,所以让它尽可能的小(即1乘1像素)并将其放置在显示器的下角:
Lets start off by creating a new figure. As we don't need the figure to display anything, let's make it as small as possible (i.e. 1 by 1 pixel) and place it at the lower corner of the display:
f = figure('Position',[0,0,1,1]);
现在,我们将图形的UserData
属性(将用作计数器)设置为零:
Now we'll set the UserData
property of the figure - which we will use as counter - to zero:
set(f,'UserData',0);
现在让我们看看按下键时的操作:我们可以创建一个小的回调函数,该函数检查被按下的按钮是否为空格,如果是这种情况,则增加UserData
计数器.我们将其称为isspace
:
Now let's see what to do when a key is pressed: We can create a small callback function which checks if the pressed button was a space and increases the UserData
counter if that was the case. We'll call that function isspace
:
function isspace(hObject,callbackData)
if get(hObject,'CurrentCharacter') == ' '
set(hObject,'UserData',get(hObject,'UserData')+1);
end
end
现在只需设置图形即可将此功能用作KeyPressFcn
,
Now simply set up the figure to use this function as KeyPressFcn
by
set(f,'KeyPressFcn',@isspace);
这已经计算了按下空格的次数.计数器的当前值由
This already counts the number of times space is pressed. The current value of the counter is read by
get(f,'UserData');
现在我们需要时间测量.这可以使用timer
完成.我们将其配置为在5秒钟后熄灭,然后在基本工作区中添加一个新值.为此,我们需要一个回调函数timerCallback.m
Now we need the time measurement. This can be done using a timer
. We'll configure it to go off after 5 seconds and then assing a new value in the base workspace. For that we need a callback function timerCallback.m
function timerCallback(hObj,eventData)
assignin('base','nSpace',get(gcf,'UserData'));
delete(gcf);
stop(hObj);
delete(hObj);
end
t = timer('StartDelay',5,'TimerFcn',@timerCallback);
start(t);
就是这样:首先创建图形,创建计时器,然后在5秒钟后在工作区的变量nSpace
中获得按键次数,并且窗口关闭.
And that's it: First create the figure, create the timer and after 5 seconds you get the number of key presses in the variable nSpace
in your workspace and the window is closed.
这篇关于如何在Matlab中检测键盘空格键按下情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!