psychopy.org | Reference | Downloads | Github

Displaying Key Press Duration to participant

Hi guys,

In my experiment, I would like to display the keypress duration time to the participant.
So far I can only display the amount of time from when the Textsim is created until the space button is released (str(i) in the code).

Just to be clear I would like where it displays the string (i) in the code to actually display from when the space bar is pressed until it is released. Is this possible?

I have attached a snippet of my code below:

Thanks in advance,

Sean

# Question Screen 
i = 0 
loop_1 = True
while loop_1: 
    instruction = visual.TextStim(win, text ='Do you prefer cats or dogs?\nOption A: Cats\n\
    Option B: Dogs\n\
    Thinking time =' + str(i) )
    instruction.draw()
    win.flip()  
    q_keys = kb.getKeys(["space"], waitRelease=True)
    if len(q_keys):
        f = ('Space_always', q_keys[0].name)
        d = ('RT1', q_keys[0].rt)
        c = ('Press Time', q_keys[0].duration)
        loop_1 = False
    i = i + 1

win.callOnFlip(kb.clock.reset) 
win.callOnFlip(kb.clearEvents, eventType='keyboard')  

# Response Screen 
instruction.text = 'Press the key "t" for Option A \n Press the key "y" for Option B '
instruction.draw()
win.flip() 

loop_2 = True
while loop_2:
    a_keys = kb.getKeys(['t', 'y'], waitRelease=False)
    if len(a_keys):
        b = ('Answer', a_keys[0].name)
        a = ('RT2', a_keys[0].rt)
        loop_2 = False


Yes, this is possible! You just need to add some custom code into the Each Frame tab of a Code Component. If we were to say that the Text Component in which you want to display the keypress duration is called text and the Keyboard Component listening for the keypress is called key_resp, then you would do this:

kp = key_resp.getKeys(waitRelease=False, clear=False)
if len(kp) > 0:
    if kp[-1].duration is None:
        dur = round(t-kp[-1].rt, 1)
        text.text = str(dur)

To run through what this does…

This gets all keypresses stored in the keyboard component:

kp = key_resp.getKeys(waitRelease=False, clear=False)

This checks that you have any keypresses to check against:

if len(kp) > 0:

This checks that the key is currently being pressed (when released, it is given duration, so when duration has not been set, the key is down):

    if kp[-1].duration is None:

This subtracts the time the last keypress started (kp[-1].rt) from the time since the routine started (t) to get the amount of time since the key was pressed:

        dur = round(t-kp[-1].rt, 1)

This sets the content of a text component to this dur value:

        text.text = str(dur)