In order to control the height of the ball from the base station, a Logitech Dual Action gamepad (essentially a PlayStation 2 controller) was used as an input device. After the hover station was activated, it proceeded to raise the ball to an initial height of 8 inches. Once this height was reached, a user could use the gamepad to lower or raise the height of the ball using buttons 2 or 4 respectively (see image below). Each button press would raise or lower the ball by 1 inch as measured through the sonar module.
To read input from the gamepad into the base station, both the Arduino Uno and the gamepad were attached by USB to a computer running a python script. Whenever a button was pressed, the python script would detect the button and send an ASCII character corresponding to the button number to the Uno via serial (e.g. ‘2’ for button 2). Since the required inputs for the ball floating apparatus were minimal, gamepad joysticks were not used. Upon receiving a character input over the serial connection, the Uno would send the character wireless to the hover station.
Gamepad Python Script
Although a Python script to read and send data from the gamepad was made available to the team from a previous project, the script was difficult to understand and highly unreliable. Therefore, a much simpler python script was created to send button presses one byte at a time to the Arduino board over a serial connection. The Python code is available below.
''' basic_control.py @author: Garrett Owen @date: January 26, 2012 Based off code from http://iamtherockstar.com/archive/making-hid-devices-easier-using-pygame-joysticks/ ''' import serial import pygame import time #serialPort = '/dev/tty.usbserial-A7004Jg4' # Arduino Mega serialPort = '/dev/tty.usbmodemfd121' # Arduino Uno baudRate = 9600 # Open Serial Connection to Arduino Board ser = serial.Serial(serialPort, baudRate, timeout=1); ''' Gets joystick data and prints it ''' pygame.init() #joystick.init() j = pygame.joystick.Joystick(0) j.init() print 'Initialized Joystick : %s' % j.get_name() # Keeps a history of buttons pressed so that one press does # not send multiple presses to the Arduino Board button_history = [0,0,0,0,0,0,0,0,0,0,0,0] try: while True: pygame.event.pump() # # Used to read input from the two joysticks # for i in range(0, j.get_numaxes()): # if j.get_axis(i) != 0.00: # print 'Axis %i reads %.2f' % (i, j.get_axis(i)) # # time.sleep(1) for i in range(0, j.get_numbuttons()): if j.get_button(i) != 0: if not button_history[i]: print 'Button %i reads %i' % (i, j.get_button(i)) button_history[i] = 1 ser.write(str(i)) else: button_history[i] = 0 except KeyboardInterrupt: j.quit()
The script automatically detects the gamepad type and inputs using a library called PyGame, which is not installed with Python by default. PySerial must also be installed to send data over the serial port to the Arduino board. The script was run using Python version 2.7.1 on Mac OS X Lion.