multiple KbChecks in one loop
24 views (last 30 days)
Show older comments
Hi,
I'm trying to collect multiple button presses per trial with KbCheck. The experimental task will be for a subject to press sequences of 6-10 numbers as fast as possible.
Here's how I think it should work, but it doesn't. For some reason, only the first button that's being pressed is collected 6x in the answer vector. It seems like the button somehow gets 'stuck', so that in the next iteration it appears to be down still.
answer = [0,0,0,0,0,0];
accepted_keys = [KbName('1!'), KbName('2@'), KbName('3#'), KbName('4$')];
responded = 0;
while responded == 0
[keyIsDown,secs, keyCode, deltaSecs] = KbCheck;
for cc = 1:length(answer)
if any(keyCode(accepted_keys))
answer(cc) = find(keyCode)
responded = 1;
end
WaitSecs(0.001)
end
end
In another attempt, I tried to collect button presses as character strings, which does the trick of collecting several button presses after another, but now it's too slow to register very fast button presses (which I suppose is due to the rather low efficiency of my loop structure).
key_answer = ['']
key = 0;
while length(key_answer) < 6
[KeyIsDown, secs, KeyCode] = KbCheck;
if KeyIsDown==1 & key==0
key=find(KeyCode)
end
if KeyIsDown==0 & key~=0
temp = KbName(key)
key_answer(end+1)=temp(1)
key=0
end
end
Does anyone have an idea how to fix it either one of them? Any help is appreciated!
1 Comment
prabhat kumar sharma
on 4 Jun 2024
I understand that initial approach with KbCheck has the right idea but needs some adjustments to accurately capture multiple button presses without getting "stuck" on the first detected key.
1.Refinement for Collecting Button Presses
answer = zeros(1,6); % Initialize answer vector
accepted_keys = [KbName('1!'), KbName('2@'), KbName('3#'), KbName('4$')];
count = 1; % To keep track of the number of accepted key presses
while count <= length(answer)
[keyIsDown, ~, keyCode] = KbCheck;
if keyIsDown
pressedKeys = find(keyCode);
% Check if any of the pressed keys are in the accepted keys
for i = 1:length(pressedKeys)
if any(pressedKeys(i) == accepted_keys)
answer(count) = pressedKeys(i);
count = count + 1;
break; % Break after registering an accepted key
end
end
% Wait until all keys are released
while KbCheck; end
end
end
2.Refinement for Collecting Button Presses as Strings
key_answer = ''; % Initialize as an empty string
while length(key_answer) < 6
[keyIsDown, ~, keyCode] = KbCheck;
if keyIsDown
key = find(keyCode);
% Assuming 'key' will only contain one element for simplicity
if ~isempty(key)
temp = KbName(key);
key_answer(end+1) = temp(1); % Append the character to the string
% Wait until all keys are released
while KbCheck; end
end
end
end
I hope it helps!
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!