functions for reading the joystick
Dependents: SnakeProjectRev1 SnakeProjectRev1
Joystick.h
- Committer:
- meurigp
- Date:
- 2016-05-05
- Revision:
- 3:ae04f59e274a
- Parent:
- 2:e444008676a4
File content as of revision 3:ae04f59e274a:
#ifndef JOYSTICK_H #define JOYSTICK_H #include "mbed.h" // change this to alter tolerance of joystick direction #define DIRECTION_TOLERANCE 0.05 // connections for joystick InterruptIn button(PTB11); AnalogIn xPot(PTB2); AnalogIn yPot(PTB3); Ticker pollJoystick; // 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 { float x; // current x value float x0; // 'centred' x value float y; // current y value float 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; int printFlag = 0; volatile int buttonFlag = 0; // function prototypes void buttonISR(); void calibrateJoystick(); void updateJoystick(); void buttonISR() { buttonFlag = 1; } // read default positions of the joystick to calibrate later readings void calibrateJoystick() { button.mode(PullDown); // 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; // read button state joystick.button = button; // 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 = LEFT; } else if ( joystick.x < DIRECTION_TOLERANCE && fabs(joystick.y) < DIRECTION_TOLERANCE) { joystick.direction = RIGHT; } else { joystick.direction = UNKNOWN; } // set flag for printing printFlag = 1; } #endif