Controlling a Raspberry Pi with a Game Pad and Controllers

in #python7 years ago (edited)

When developing games or robots, at some point keyboard control, and being tethered by wires for that matter, is not going to cut it.

Fortunately, some generous developers have made it easy for us to control our Pi using off the shelf games controllers.

Wireless Game Pad Controller

I bought a 2.4ghz/bluetooth controller

https://amzn.to/2EGSxhQ

They are advertised as for PC and Android, and come with a dongle to insert into the USB port, making set up plug and play.

Game Controller Python Module

The module we will use is called evdev (short for 'event device').

Install it in the usual way:

sudo pip3 install evdev

Device Detection

Next find out how your device is being recognised:

import evdev

for device in evdev.list_devices():
        print(evdev.InputDevice(device))

input()

device.png

Checking Movements and Buttons

Once you have that info, now you can start recognising button presses and joystick movements!

from evdev import InputDevice

# create object to read input - specify YOUR device
controller = InputDevice('/dev/input/event0')

# want to display ALL info?
debug = False

# what are the controller details?
print(controller)

# read controller info in an infinite loop
for event in controller.read_loop():

    # here I am looking for the start button
    # so I can quit
    if event.type == 1:
        exit()

    # set as true above if you want to look up
    # different button values
    if debug:
        print("\n\nEvent Type:{}".format(event.type))
        print("Event Code:{}".format(event.code))
        print("Event Value:{}".format(event.value))

    # look for pad moves
    if event.type == 3:

        # up and down is 17
        if event.code == 17:
            if event.value == -1:
                print("\n\n\nPad Up\n")
            if event.value == 1:
                print("\n\n\nPad Down\n")

        # left and right is 16
        if event.code == 16:
            if event.value == -1:
                print("\n\n\nPad Left\n")
            if event.value == 1:
                print("\n\n\nPad Right\n")

Sort:  

Nice project. This wonderful chip (broadcom soc) is doing a good job. And the 4-core processor offers great convenience. Good luck dude. I look forward to good projects. :) @makerhacks

Coin Marketplace

STEEM 0.13
TRX 0.34
JST 0.036
BTC 109045.05
ETH 4404.36
USDT 1.00
SBD 0.83