Skip to content Skip to sidebar Skip to footer

Psychopy Key Down Code Using Iohub

I am trying to write a code in which the user is able to adjust the length of a line with the up and down arrow keys. I am able to have the user adjust the line by pressing them,

Solution 1:

This answer assumes you are using PsychoPy's Builder interface. But you can just put the same code snippets at appropriate places within the Coder interface as well.

I assume you have a Line component, and that its size is specified in normalised units. Now insert a Code component (after it is created, right-click on it and move it above the Line component so that changes to the Line object get applied immediately rather than on the next screen refresh).

In the Code component's "Begin Experiment" tab, put this code to initialise ioHub and to create an initial value for the scaling factor that will be applied to the line (defaults to zero):

from psychopy.iohub import launchHubServer, EventConstants

io=launchHubServer(experiment_code='key_evts', psychopy_monitor_name='default')
keyboard = io.devices.keyboard

increment = [0, 0] # initial value of scaling factor

Then in the "Each frame" tab, we will check for key presses. So if your screen is running at 60 Hz, that is the rate at which the line size will be updated.

# check the keyboardfor event in keyboard.getEvents():
    if event.type == EventConstants.KEYBOARD_PRESS:
    # a key has been pressed. This is reported only once, so set the value # of the scaling factor to be used until the key is released:if event.key == u'UP':
            increment = [0.01, 0] # make it 1% of screen half-width longerelif event.key == u'DOWN':
            increment = [-0.01, 0] # make 1% shorterif event.type == EventConstants.KEYBOARD_RELEASE:
    # the key is no longer being pressed, so stop changing the size:
        increment = [0, 0]

# regardless of what key is/isn't pressed, apply the current# scaling factor on every screen refresh
line.size += increment

Hope that works for you. (I'm a novice at using ioHub: this works for me but may not be the "correct" way to do it).

Post a Comment for "Psychopy Key Down Code Using Iohub"