psychopy.org | Reference | Downloads | Github

End routine after one or two keyboard events

Hello everybody,

I’m fairly new to python and coding in general, so by all means point out anything nonsensical in my code.
I am currently working on an experiment in which participants can respond with one key press (e.g. left), another key press (e.g. right) or both keys at (roughly) the same time.
The routine should end some 250ms after one, the other or both key presses have been detected. Thus it should not end right after one key has been pressed, but there should be a little tolerance for the second key press.
So far I have a code component with the following in the ‘each frame’ section:

keyList = event.getKeys()
if keyList: # check for any key press

if "left" in keyList and "right" in keyList: #both keys have been pressed
action = "dual" #my attempt to store in a single variable whether one, the other or both keys have been pressed
core.wait(.25)
continueRoutine = False                             
     
elif "left" in keyList and not("right" in keyList): #what to do in case only the left key has been pressed
action = "single_left"
core.wait(.25)
continueRoutine = False
                   
elif "right" in keyList and not("left" in keyList): #what to do in case only the right key has been pressed
action = "single_right"
core.wait(.25)
continueRoutine = False

Like this, it correctly sets the action variable for dual key presses but only when both keys are pressed nearly simultaneously. From what I’ve read in the forum so far, I don’t even think I should include core.wait() in the ‘each frame’ section but I don’t really understand why yet.

So my main question is how to give the routine ‘a little room’ to detect a second key press but also terminate after 250ms when only one key has been pressed.

Thank you for any ideas and advice!

What you should be doing is resetting a timer when one key is pressed and then ending the routine if a key has been pressed and.25 seconds have passed.

Thanks for the quick reply! I already tried that but resetting the timer within the “each frame” section when a key is pressed didn’t work - i guess because it’s getting reset all the time. Did you mean putting it in that section?

It will work in Each Frame but you might need a flag to count key presses and ignore duplicates.

That did the trick. Many thanks!