Suppressing a specific key press in PsychToolBox

896 views Asked by At

We are preparing a Likert type scale. Subjects must be allowed to just press the numbers of 1-9. We know ListenChar but it suppresses the whole keyboard. How can we suppress non-number keys?

while(1)
    ch = GetChar;
    if ch == 10 %return is 10 or 13
        %terminate
        break
    else
        response=[response ch];
    end
end
2

There are 2 answers

0
Ian Riley On BEST ANSWER

If you only want to accept keypresses 1-9:

while(1)
    ch = GetChar;
    if ch == 10 %return is 10 or 13
        %terminate
        break
    elseif (ch>48) & (ch<58) %check if the char is a number 1-9
        response=[response ch];
        pause(0.1) %delay 100ms to debounce and ensure that we don't count the same character multiple times
    end
end

I also added a debounce, so that you don't accidentally log a single input many times.

0
alexforrence On

Psychtoolbox includes functionality, via RestrictKeysForKbCheck, to restrict listening to specific keys.

The following code restricts possible inputs from 1-9, plus the esc key:

KbName('UnifyKeyNames'); % use internal naming to support multiple platforms
nums = '123456789';
keynames = mat2cell(nums, 1, ones(length(nums), 1));
keynames(end + 1) = {'ESCAPE'};
RestrictKeysForKbCheck(KbName(keynames));

Below is a trivial example of a block:

response = repmat('x', 1, 10); % pre-allocate response, similar to OP example

for ii = 1:10
    [~, keycode] = KbWait(); % wait until specific key press
    keycode = KbName(keycode); % convert from key code to char
    disp(keycode);

    if strcmp(keycode, 'ESCAPE')
        break;
    else
        response(ii) = KbName(keycode);
    end
    WaitSecs(0.2); % debounce
end

RestrictKeysForKbCheck([]); % re-enable all keys