matlabkeywaitpsychtoolbox

Wait until user presses key


I’m doing a project where I have a visual stimulus which consists of many dots moving around in the screen in a specific direction, and after the stimulus, the user needs to press one of two keys (either ‘q’ or ‘w’).

I want the user to be forced to press the key, that is: the stimulus (dots moving in a specific direction) plays for a fixed duration, then it stops (but the dots keep moving in random directions) and it just stays like that until the user presses ‘q’ or ‘w’. After the user finally presses a key, there’s an auditory feedback (correct or wrong answer) and the stimulus plays again. This repeats until the end of the trials.

My question is, how can I force the user to press a key, after the stimulus, without pausing? Because if I pause, all the dots ‘freeze’, instead of moving around in different/random directions while waiting for an answer. So, how can I wait “forever/indefinitely” until the user presses the key (‘q’ or ‘w’)?

My code:

% present dots in random directions:
for frame = 1:ceil(maxRT*frameRate) %maxRT is 2 seconds
        %calls function related to the drawing of the dots            
        Screen('DrawingFinished', window1.h);
            [flip.waitRT.VBL(block, trial, frame), ...
                flip.waitRT.StimOns(block, trial, frame), ...
                flip.waitRT.FlipTS(block, trial, frame), ...
                flip.waitRT.Missed(block, trial, frame), ...
                flip.waitRT.beampos(block, trial, frame)] = Screen('Flip', window1.h, TimingCnt);
            TimingCnt = flip.waitRT.VBL(block, trial, frameNum) + window1.frameDur - window1.slack; 

        [keyIsDown, secs, keyCode]  = KbCheck();
        keypressed = KbName(keyCode);
        if ischar(keypressed) && ~isempty(keypressed) && keyIsDown
            %checks which key was pressed, compares pressed key with correct key to check if it's correct or wrong, calculates RT, plays auditory feedback
        end
end

Solution

  • http://psychtoolbox.org/docs/KbWait

    Use KbWait function in a while loop providing untilTime parameter as 10ms. If the keyCode is valid, break and proceed accordingly.

    Example pseudo code:

    isValid = false;
    while ~isValid
        % move dots randomly
        [secs, keyCode, deltaSecs] = KbWait('untilTime', 0.01);
        if (keyCode == 'q') || (keyCode == 'w')
            isValid = true;
        end
    end
    % do stuff