My ELEC2645 joystick project Tetris Game NAME: JIANWEI CHEN SID: 200879849
Dependencies: N5110 SDFileSystem mbed
Joystick.h
- Committer:
- cjw851102
- Date:
- 2016-05-05
- Revision:
- 4:463abe5f5135
File content as of revision 4:463abe5f5135:
/** @file Joystick.h @brief Header file containing functions prototypes, defines and global variables for constructing joystick. @brief Example code of how to read a joystick with slightly changed for the game @https://www.sparkfun.com/products/9032 @author Craig A. Evans @date 7 March 2015 */ #ifndef JOYSTICK_H #define JOYSTICK_H #define DIRECTION_TOLERANCE 0.25 /** Joystick vertical direction @brief Analog input for joystick to send vertical directions data */ AnalogIn yPot(PTB2); /** Joystick horizontal direction @brief Analog input for joystick to send horizontal direction data */ AnalogIn xPot(PTB3); //! create enumerated type (0,1,2,3 etc. for direction) //! could be extended for diagonals etc. enum DirectionName { UP, DOWN, LEFT, RIGHT, CENTRE, UNKNOWN }; //! struct for Joystick typedef struct JoyStick Joystick; struct JoyStick { double x; // current x value double x0; // 'centred' x value double y; // current y value double y0; // 'centred' y value int button; // button state (assume pull-down used, so 1 = pressed, 0 = unpressed) DirectionName direction; // current direction }; //! create struct variable Joystick joystick; /** Read default positions of the joystick to calibrate later readings */ void calibrateJoystick(); /** Update the current position of joystick */ void updateJoystick(); ///////////////////////////////////////////////// /// Function Definitions ///////////////////////////////////////////////// // read default positions of the joystick to calibrate later readings void calibrateJoystick() { // must not move during calibration joystick.x0 = xPot; // initial positions in the range 0.0 to 1.0 (0.5 if centred exactly) joystick.y0 = yPot; } void updateJoystick() { // read current joystick values relative to calibrated values (in range -0.5 to 0.5, 0.0 is centred) joystick.x = xPot - joystick.x0; joystick.y = yPot - joystick.y0; // calculate direction depending on x,y values // tolerance allows a little lee-way in case joystick not exactly in the stated direction if ( fabs(joystick.y) < DIRECTION_TOLERANCE && fabs(joystick.x) < DIRECTION_TOLERANCE) { joystick.direction = CENTRE; } else if ( joystick.y < DIRECTION_TOLERANCE && fabs(joystick.x) < DIRECTION_TOLERANCE) { joystick.direction = UP; } else if ( joystick.y > DIRECTION_TOLERANCE && fabs(joystick.x) < DIRECTION_TOLERANCE) { joystick.direction = DOWN; } else if ( joystick.x < DIRECTION_TOLERANCE && fabs(joystick.y) < DIRECTION_TOLERANCE) { joystick.direction = RIGHT; } else if ( joystick.x > DIRECTION_TOLERANCE && fabs(joystick.y) < DIRECTION_TOLERANCE) { joystick.direction = LEFT; } else { joystick.direction = UNKNOWN; } } #endif