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!
