Wishful Coding

Didn't you ever wish your
computer understood you?

Gamepad remote control

I had this pincer bot that I had not yet programmed, but using software remotes proved disappointing. With a few lines of code, I was able to use any gamepad or joystick to control the robot.

To use this code, you need to know how to execute commands on your computer. Then, do the following.

  1. Install Python if you don't already have it.
  2. Install PyGame for interfacing with the gamepad.
  3. Install NXT-python for interfacing with the NXT.
  4. Make sure your NXT and gamepad are connected and working.
  5. Run
    python nxtjoy.py
    in the directory where you've downloaded the code below.
The code assumes you have the pincer bot in the video, for which I'll give you instructions later. Moving around should work with most tank-steered robots.
import pygame
from nxt import locator, motor
from time import sleep

# edit this to reflect your joystick axis and buttons
axis = {'x':0, 'y':1}

b = locator.find_one_brick()

left = motor.Motor(b, motor.PORT_B)
right = motor.Motor(b, motor.PORT_A)
action = motor.Motor(b, motor.PORT_C)

closed = False

def limit(nr):
    if nr > 50 or nr < -50:
        return min(127, max(-128, nr))
        return 0

def move(fwd=0, turn=0):
    lp = int((fwd - turn) * -100)
    rp = int((fwd + turn) * -100)

def pincer(button):
    global closed
        if button and not closed:
            closed = True
            action.turn(-40, 70, emulate=False)
        elif not button and closed:
            closed = False
            action.turn(30, 70, emulate=False, brake=False)
    except motor.BlockedException:
        print action.get_tacho()

j = pygame.joystick.Joystick(0) # first joystick
print 'Initialized Joystick : %s' % j.get_name()
    while True:

        # get_axis returns a value between -1 and 1
        move(j.get_axis(axis['y']), j.get_axis(axis['x']))

except KeyboardInterrupt:
Published on