How can I check if a key was hit in psychopy?

Dear Users,

How can you check in Psychopy if a key was hit? Shouldn’t that simply be possible with:

b = event.getKeys()
if len(b) == 0:
##no key was hit##

??

Yes, but people can spend a lot of time not responding. This is an instantaneous check (i.e. “has the subject pressed a key since I last checked?”).

You should probably give us more details of the issue you are facing.

Alright, attached you can find the code of my program so far (lines of interest = 185-191). The idea of that code is that a message (‘TOO SLOW’) should show up after 800 ms in a trial, if no key was hit in that trial. If I run the code however, the message simply shows up after 800 ms in each trial, no matter if a key was hit before or not. That’s why I thought I probably just don’t get how to make psychopy understand that a key was hit in the previous 800 ms of a trial. Could you may have a look at lines 185-191 of the code and see if u find the error? Thanks already in advance!! Instant_Errormessage.py (9.8 KB)

It generally isn’t a great idea to edit Builder code directly. You’d be much better off using a code component within the Builder interface. At the moment your code breaks a lot of what Builder does (e.g. you can’t just insert timers in your own code, it breaks all of Builder’s timing.

What you probably want to do here in Builder is split you trial into two routines. The first ends at 800 ms or on a keypress. Make the second one contingent on whether a keypress was detected in the first one. e.g. on the second routine, put something like this in a code component in the “Begin routine” tab:

if len(your_keyboard_compoenent_name.keys) != 0:
    continueRoutine = False

Hi Michael,

Thanks for your reply!

Yeah that’s exactly what I thought, which is why I tried to find a new solution, just using the clocks coded through the Builder, and I actually found sth in that way (what’s your opinion; am I still breaking the Builder’s timing with the new code lines around 180-200?)

Meanwhile I think, even if its implementation in the builder code, this solution maybe doesn’t break the builder’s timing. The reason is, I think, (see the code lines around 180-200) because I avoided creating new counters / clocks; but I simply used the trialclocks defined through the Builder to set new textstimuli durations may coming up (for the TOO SLOW and the WRONG message, I simply used the remaining RoutineTimer of the running trial as clock / duration definition, as you’ll see in the code lines 180-200).

Am I right that this solution doesn’t break the Builder’s timing in any way anymore?

Cheers

Instant_Errormessage_final_real.py (9.7 KB)

By the way, it also looks way smoother and regular when you run the script now, compared to before! Also, the TOO SLOW message works perfectly now (if you hit a key before 800ms, it won’t show up).