joystick (pyglet and pygame)

AT THE MOMENT JOYSTICK DOES NOT APPEAR TO WORK UNDER PYGLET. We need someone motivated and capable to go and get this right (problem is with event polling under pyglet)

Control joysticks and gamepads from within PsychoPy.

For most backends, you do need a window using the same backend (and you need to be flipping it) for the joystick to be updated.

exception psychopy.hardware.joystick.JoysticButtonNotAvailableError[source]

Exception raised when a button is not available on the joystick.

class psychopy.hardware.joystick.Joystick(device=0, **kwargs)[source]

Class for interfacing with a multi-axis joystick or gamepad.

Upon creating a Joystick object, the joystick device is opened and the states of the device’s axes and buttons can be read.

Values for the axes are returned as floating point numbers, typically between -1.0 and +1.0 unless scaling is applied. The values for the buttons are returned as booleans, where True indicates the button is pressed down at the time the device was last polled.

Scaling factors can be set for each axis to adjust the range of the axis values. The scaling factor is a floating point value that is multiplied by the axis value. If the scaling factor is negative, the axis value is inverted. Deadzones can also be applied for each axis to prevent small fluctuations in the joystick’s resting position from being interpreted as valid input. The deadzone is a floating point value between 0.0 and 1.0. If the absolute value of the axis value is less than the deadzone, the axis value is set to zero.

Device inputs can be named to provide a more human-readable interface. The names can be set for axes, buttons, and hats where they can be used to get the input values instead of using the integer indices. Furthermore, like inputs can be grouped together under a single name. For example, both X and Y of a thumbstick can be grouped together under the name ‘thumbstick’. When getting the value of the thumbstick, a tuple of the X and Y values is returned instead of having to get each axis individually.

Parameters:

device (int or str) – The index or name of the joystick to control.

Examples

Typical usage:

from psychopy.hardware import joystick
from psychopy import visual

joystick.backend='pyglet'  # must match the Window
win = visual.Window([400,400], winType='pyglet')

nJoys = joystick.getNumJoysticks()  # to check if we have any
id = 0
joy = joystick.Joystick(id)  # id must be <= nJoys - 1

nAxes = joy.getNumAxes()  # for interest
while True:  # while presenting stimuli
    joyX = joy.getX()
    # ...
    win.flip()  # flipping implicitly updates the joystick info

Set the deadzone for axis 0 to 0.1:

joy.setAxisDeadzone(0, 0.1)

Set the scaling factor for 1 axis to 2.0:

joy.setAxisScale(1, 2.0)

Setting the names of the inputs can be useful for debugging and for providing a more human-readable interface:

joy.setInputName('axis', 0, 'x')
joy.setInputName('axis', 1, 'y')

You can get the imput value by name by passing it to the get method for the input type:

joy.getAxis('axis', 'x')  # instead of joy.getAxis(0)

Automatically set the input names to the default Xbox controller mapping scheme:

joy.setInputScheme('xbox')
# ...
xVal, yVal = joy.getAxis('left_thumbstick')
leftTrigger, rightTrigger = joy.getAxis('triggers')

Notes

  • You do need to be flipping frames (or dispatching events manually) in order for the values of the joystick to be updated.

  • Currently under pyglet backends the axis values initialise to zero rather than reading the current true value. This gets fixed on the first change to each axis.

  • Currently pygame (1.9.1) spits out lots of debug messages about the joystick and these can’t be turned off :-/

  • The GLFW backend can be used without first opening a window and can be used with other window backends.

_getIndexFromName(inputType, name)[source]

Get the index of an input from its name.

Parameters:
  • inputType (str) – The type of input to get the index for. Must be one of ‘axis’, ‘button’, or ‘hat’.

  • name (str) – The name of the input to get the index for.

Returns:

The index of the input. If the input name is not found, None is returned.

Return type:

int or None

Raises:

InvalidInputNameError – If the input name is not valid or has not been set.

close()[source]

Close the joystick device.

property deviceIndex

The index of the joystick (int).

getAllAxes()[source]

Get a list of all current axis values (int).

getAllButtons()[source]

Get the state of all buttons on the devics.

Returns:

A list of button states. Each state is a boolean.

Return type:

list

getAllHats()[source]

Get the current values of all available hats.

Returns:

Each value is a tuple (x, y) where x and y axis states are trinary (-1, 0, +1)

Return type:

list

static getAvailableDevices()[source]

Return a list of available joystick devices.

This method is used by DeviceManager to get a list of available devices.

Returns:

A list of available joystick devices.

Return type:

list

getAxis(axisId)[source]

Get the value of an axis by an integer id.

Parameters:

axisId (int, str or list) – The axis ID to get the value for. If a string is supplied, the name of the axis is used to get the value. If a list of axes indices or names is supplied, a list of values is returned.

Returns:

The value of the axis. If a list of axes is supplied, a list of values is returned.

Return type:

float or list

getAxisDeadzone(axisId)[source]

Get the deadzone for a given axis.

Parameters:

axisId (int) – The axis ID to get the deadzone for.

Returns:

The deadzone for the given axis.

Return type:

float

getAxisScale(axisId)[source]

Get the scale factor for a given axis.

Parameters:

axisId (int) – The axis ID to get the scale factor for.

Returns:

The scale factor for the given axis.

Return type:

float

getButton(buttonId)[source]

Get the state of a given button on the device (bool).

Parameters:

buttonId (int, str or list) – The button ID to get the state for. If a string is supplied, the name of the button is used to get the state. If a list of button indices or names is supplied, a list of states is returned.

Returns:

The state of the button. If a list of buttons was passed as buttonId, a list of states is returned where each state is a boolean.

Return type:

bool or list

getHat(hatId=0)[source]

Get the position of a particular hat.

Parameters:

hatId (int or str) – The hat ID to get the position for. If a string is supplied, the name of the hat is used to get the position.

Returns:

The position returned is an (x, y) tuple where x and y can be -1, 0 or +1.

Return type:

tuple

getName()[source]

Return the manufacturer-defined name describing the device (str).

getNumAxes()[source]

Get the number of available joystick axes.

The first axis usually corresponds to the X axis, the second to the Y axis for most joysticks. Additional axes may be present for other controls such as addtional thumbsticks or throttle lever.

Returns:

The number of axes found on the joystick.

Return type:

int

getNumButtons()[source]

Get the number of buttons on the device (int).

Returns:

The number of buttons on the joystick.

Return type:

int

getNumHats()[source]

Get the number of hats on this joystick.

The GLFW backend makes no distinction between hats and buttons. Calling ‘getNumHats()’ will return 0.

getRX()[source]

Return the RX axis value (equivalent to joystick.getAxis(3)).

getRY()[source]

Return the RY axis value (equivalent to joystick.getAxis(4)).

getRZ()[source]

Return the RZ axis value (equivalent to joystick.getAxis(5)).

getX()[source]

Return the X axis value (equivalent to joystick.getAxis(0)).

getXY()[source]

Return the X and Y axis values as a tuple.

Returns:

The X and Y axis values as a tuple.

Return type:

tuple

getY()[source]

Return the Y axis value (equivalent to joystick.getAxis(1)).

getZ()[source]

Return the Z axis value (equivalent to joystick.getAxis(2)).

property hasTracking

Check if the joystick has tracking capabilities.

Returns:

True if the joystick has tracking capabilities, False otherwise.

Return type:

bool

property inputLib

Input interface library used (str).

property isOpen

Check if the joystick device is open.

Returns:

True if the joystick device is open, False otherwise.

Return type:

bool

isSameDevice(otherDevice)[source]

Check if the device is the same as another device.

Parameters:

otherDevice (Joystick) – The other device to compare against.

Returns:

True if the devices are the same, False otherwise.

Return type:

bool

lastUpdateTime()[source]

Return the time of the last update to the joystick state.

Returns:

The time of the last update to the joystick state.

Return type:

float

property name

Name of the joystick reported by the system (str).

open()[source]

Open the joystick device.

poll()[source]

Poll the joystick device for the current state.

This method should be called at the beginning of each frame to update the state of the joystick device. The time of the last update is stored and can be accessed using the lastUpdateTime property.

property rx

The RX axis value (float).

property ry

The RY axis value (float).

property rz

The RZ axis value (float).

setAxisDeadzone(axisId=None, deadzone=0.1)[source]

Set the deadzone for a given axis.

Parameters:
  • axisId (int, str, list or None) – The axis ID to set the deadzone for. If None, set the deadzone for all axes to the given value. A string can be supplied to set the deadzone for an axis by name. A list of axes can also be supplied to set the deadzone for multiple axes at once.

  • deadzone (float) – The deadzone to set, must be between 0.0 and 1.0.

setAxisScale(axisId, scale)[source]

Set the scale factor for a given axis.

Parameters:
  • axisId (int or None) – The axis ID to set the scale factor for. If None, set the scale factor for all axes to the given value.

  • scale (float) – The scale factor to set. This factor will be multiplied by the axis value. If negative, the axis value will be inverted.

setInputName(inputType, inputIndex, name)[source]

Set the name of an input.

Parameters:
  • inputType (str) – The type of input to set the name for. Must be one of ‘axis’, ‘button’, or ‘hat’.

  • inputIndex (int or list of int) – The index of the input to set the name for. If a list of indices is supplied, multiple axes will be grouped together.

  • name (str or None) – The name to set for the axis. If None, the name for the axis is removed.

Raises:

ValueError – If the inputType is not ‘axis’, ‘button’, or ‘hat’.

Examples

Set the name of axis 0 to ‘x’ and get its value by name:

joy.setInputName('axis', 0, 'x')
xVal = joy.getAxis('x')  # instead of joy.getAxis(0)

Joystick inputs often have multiple axes ganged together on a single control, such as a thumbstick. You can group axes together by passing a list of indices:

joy.setInputName('axis', [0, 1], 'left_thumbstick')
xVal, yVal = joy.getAxis('left_thumbstick')  # returns 2 values
setInputScheme(mapping)[source]

Set the input mapping scheme for the joystick.

The input mapping scheme determines the names of the inputs for the joystick. The mapping scheme can be set to ‘default’, ‘xbox’, or ‘custom’. The default mapping scheme provides names for the axes and buttons that are common to most joysticks.

Note that setting the mapping scheme will overwrite any custom input names that have been set prior to calling this method.

Parameters:

mapping (str) – The mapping scheme to set. Must be one of ‘default’, ‘xbox’, or ‘custom’.

property trackerData

Tracker data for the controller.

Returns:

The tracker data.

Return type:

TrackerData or None

property x

The X axis value (float).

property y

The Y axis value (float).

property z

The Z axis value (float).

exception psychopy.hardware.joystick.JoystickAxisNotAvailableError[source]

Exception raised when an axis is not available on the joystick.

exception psychopy.hardware.joystick.JoystickError[source]

Exception raised for errors in the joystick module.

psychopy.hardware.joystick.getJoystickInterfaces()[source]

Get available joystick input interfaces.

Returns:

A mapping of joystick interfaces available where the key is the input library identifier and the value is the joystick interface class. Setting the backend to one of these keys will use the corresponding joystick interface.

Return type:

dict

class psychopy.hardware.joystick.Joystick(device=0, **kwargs)[source]

Class for interfacing with a multi-axis joystick or gamepad.

Upon creating a Joystick object, the joystick device is opened and the states of the device’s axes and buttons can be read.

Values for the axes are returned as floating point numbers, typically between -1.0 and +1.0 unless scaling is applied. The values for the buttons are returned as booleans, where True indicates the button is pressed down at the time the device was last polled.

Scaling factors can be set for each axis to adjust the range of the axis values. The scaling factor is a floating point value that is multiplied by the axis value. If the scaling factor is negative, the axis value is inverted. Deadzones can also be applied for each axis to prevent small fluctuations in the joystick’s resting position from being interpreted as valid input. The deadzone is a floating point value between 0.0 and 1.0. If the absolute value of the axis value is less than the deadzone, the axis value is set to zero.

Device inputs can be named to provide a more human-readable interface. The names can be set for axes, buttons, and hats where they can be used to get the input values instead of using the integer indices. Furthermore, like inputs can be grouped together under a single name. For example, both X and Y of a thumbstick can be grouped together under the name ‘thumbstick’. When getting the value of the thumbstick, a tuple of the X and Y values is returned instead of having to get each axis individually.

Parameters:

device (int or str) – The index or name of the joystick to control.

Examples

Typical usage:

from psychopy.hardware import joystick
from psychopy import visual

joystick.backend='pyglet'  # must match the Window
win = visual.Window([400,400], winType='pyglet')

nJoys = joystick.getNumJoysticks()  # to check if we have any
id = 0
joy = joystick.Joystick(id)  # id must be <= nJoys - 1

nAxes = joy.getNumAxes()  # for interest
while True:  # while presenting stimuli
    joyX = joy.getX()
    # ...
    win.flip()  # flipping implicitly updates the joystick info

Set the deadzone for axis 0 to 0.1:

joy.setAxisDeadzone(0, 0.1)

Set the scaling factor for 1 axis to 2.0:

joy.setAxisScale(1, 2.0)

Setting the names of the inputs can be useful for debugging and for providing a more human-readable interface:

joy.setInputName('axis', 0, 'x')
joy.setInputName('axis', 1, 'y')

You can get the imput value by name by passing it to the get method for the input type:

joy.getAxis('axis', 'x')  # instead of joy.getAxis(0)

Automatically set the input names to the default Xbox controller mapping scheme:

joy.setInputScheme('xbox')
# ...
xVal, yVal = joy.getAxis('left_thumbstick')
leftTrigger, rightTrigger = joy.getAxis('triggers')

Notes

  • You do need to be flipping frames (or dispatching events manually) in order for the values of the joystick to be updated.

  • Currently under pyglet backends the axis values initialise to zero rather than reading the current true value. This gets fixed on the first change to each axis.

  • Currently pygame (1.9.1) spits out lots of debug messages about the joystick and these can’t be turned off :-/

  • The GLFW backend can be used without first opening a window and can be used with other window backends.

_getIndexFromName(inputType, name)[source]

Get the index of an input from its name.

Parameters:
  • inputType (str) – The type of input to get the index for. Must be one of ‘axis’, ‘button’, or ‘hat’.

  • name (str) – The name of the input to get the index for.

Returns:

The index of the input. If the input name is not found, None is returned.

Return type:

int or None

Raises:

InvalidInputNameError – If the input name is not valid or has not been set.

close()[source]

Close the joystick device.

property deviceIndex

The index of the joystick (int).

getAllAxes()[source]

Get a list of all current axis values (int).

getAllButtons()[source]

Get the state of all buttons on the devics.

Returns:

A list of button states. Each state is a boolean.

Return type:

list

getAllHats()[source]

Get the current values of all available hats.

Returns:

Each value is a tuple (x, y) where x and y axis states are trinary (-1, 0, +1)

Return type:

list

static getAvailableDevices()[source]

Return a list of available joystick devices.

This method is used by DeviceManager to get a list of available devices.

Returns:

A list of available joystick devices.

Return type:

list

getAxis(axisId)[source]

Get the value of an axis by an integer id.

Parameters:

axisId (int, str or list) – The axis ID to get the value for. If a string is supplied, the name of the axis is used to get the value. If a list of axes indices or names is supplied, a list of values is returned.

Returns:

The value of the axis. If a list of axes is supplied, a list of values is returned.

Return type:

float or list

getAxisDeadzone(axisId)[source]

Get the deadzone for a given axis.

Parameters:

axisId (int) – The axis ID to get the deadzone for.

Returns:

The deadzone for the given axis.

Return type:

float

getAxisScale(axisId)[source]

Get the scale factor for a given axis.

Parameters:

axisId (int) – The axis ID to get the scale factor for.

Returns:

The scale factor for the given axis.

Return type:

float

getButton(buttonId)[source]

Get the state of a given button on the device (bool).

Parameters:

buttonId (int, str or list) – The button ID to get the state for. If a string is supplied, the name of the button is used to get the state. If a list of button indices or names is supplied, a list of states is returned.

Returns:

The state of the button. If a list of buttons was passed as buttonId, a list of states is returned where each state is a boolean.

Return type:

bool or list

getHat(hatId=0)[source]

Get the position of a particular hat.

Parameters:

hatId (int or str) – The hat ID to get the position for. If a string is supplied, the name of the hat is used to get the position.

Returns:

The position returned is an (x, y) tuple where x and y can be -1, 0 or +1.

Return type:

tuple

getName()[source]

Return the manufacturer-defined name describing the device (str).

getNumAxes()[source]

Get the number of available joystick axes.

The first axis usually corresponds to the X axis, the second to the Y axis for most joysticks. Additional axes may be present for other controls such as addtional thumbsticks or throttle lever.

Returns:

The number of axes found on the joystick.

Return type:

int

getNumButtons()[source]

Get the number of buttons on the device (int).

Returns:

The number of buttons on the joystick.

Return type:

int

getNumHats()[source]

Get the number of hats on this joystick.

The GLFW backend makes no distinction between hats and buttons. Calling ‘getNumHats()’ will return 0.

getRX()[source]

Return the RX axis value (equivalent to joystick.getAxis(3)).

getRY()[source]

Return the RY axis value (equivalent to joystick.getAxis(4)).

getRZ()[source]

Return the RZ axis value (equivalent to joystick.getAxis(5)).

getX()[source]

Return the X axis value (equivalent to joystick.getAxis(0)).

getXY()[source]

Return the X and Y axis values as a tuple.

Returns:

The X and Y axis values as a tuple.

Return type:

tuple

getY()[source]

Return the Y axis value (equivalent to joystick.getAxis(1)).

getZ()[source]

Return the Z axis value (equivalent to joystick.getAxis(2)).

property hasTracking

Check if the joystick has tracking capabilities.

Returns:

True if the joystick has tracking capabilities, False otherwise.

Return type:

bool

property inputLib

Input interface library used (str).

property isOpen

Check if the joystick device is open.

Returns:

True if the joystick device is open, False otherwise.

Return type:

bool

isSameDevice(otherDevice)[source]

Check if the device is the same as another device.

Parameters:

otherDevice (Joystick) – The other device to compare against.

Returns:

True if the devices are the same, False otherwise.

Return type:

bool

lastUpdateTime()[source]

Return the time of the last update to the joystick state.

Returns:

The time of the last update to the joystick state.

Return type:

float

property name

Name of the joystick reported by the system (str).

open()[source]

Open the joystick device.

poll()[source]

Poll the joystick device for the current state.

This method should be called at the beginning of each frame to update the state of the joystick device. The time of the last update is stored and can be accessed using the lastUpdateTime property.

property rx

The RX axis value (float).

property ry

The RY axis value (float).

property rz

The RZ axis value (float).

setAxisDeadzone(axisId=None, deadzone=0.1)[source]

Set the deadzone for a given axis.

Parameters:
  • axisId (int, str, list or None) – The axis ID to set the deadzone for. If None, set the deadzone for all axes to the given value. A string can be supplied to set the deadzone for an axis by name. A list of axes can also be supplied to set the deadzone for multiple axes at once.

  • deadzone (float) – The deadzone to set, must be between 0.0 and 1.0.

setAxisScale(axisId, scale)[source]

Set the scale factor for a given axis.

Parameters:
  • axisId (int or None) – The axis ID to set the scale factor for. If None, set the scale factor for all axes to the given value.

  • scale (float) – The scale factor to set. This factor will be multiplied by the axis value. If negative, the axis value will be inverted.

setInputName(inputType, inputIndex, name)[source]

Set the name of an input.

Parameters:
  • inputType (str) – The type of input to set the name for. Must be one of ‘axis’, ‘button’, or ‘hat’.

  • inputIndex (int or list of int) – The index of the input to set the name for. If a list of indices is supplied, multiple axes will be grouped together.

  • name (str or None) – The name to set for the axis. If None, the name for the axis is removed.

Raises:

ValueError – If the inputType is not ‘axis’, ‘button’, or ‘hat’.

Examples

Set the name of axis 0 to ‘x’ and get its value by name:

joy.setInputName('axis', 0, 'x')
xVal = joy.getAxis('x')  # instead of joy.getAxis(0)

Joystick inputs often have multiple axes ganged together on a single control, such as a thumbstick. You can group axes together by passing a list of indices:

joy.setInputName('axis', [0, 1], 'left_thumbstick')
xVal, yVal = joy.getAxis('left_thumbstick')  # returns 2 values
setInputScheme(mapping)[source]

Set the input mapping scheme for the joystick.

The input mapping scheme determines the names of the inputs for the joystick. The mapping scheme can be set to ‘default’, ‘xbox’, or ‘custom’. The default mapping scheme provides names for the axes and buttons that are common to most joysticks.

Note that setting the mapping scheme will overwrite any custom input names that have been set prior to calling this method.

Parameters:

mapping (str) – The mapping scheme to set. Must be one of ‘default’, ‘xbox’, or ‘custom’.

property trackerData

Tracker data for the controller.

Returns:

The tracker data.

Return type:

TrackerData or None

property x

The X axis value (float).

property y

The Y axis value (float).

property z

The Z axis value (float).


Back to top