Mark Peter Vargha / Joystick
Revision:
0:f76f52dc57f7
Child:
1:a768d268191b
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Joystick.h	Thu Feb 09 19:13:02 2017 +0000
@@ -0,0 +1,129 @@
+#ifndef Joystick_h
+#define Joystick_h
+
+#include "mbed.h"
+
+#ifndef JOYSTICK_CALIBRATION_CYCLES
+#define JOYSTICK_CALIBRATION_CYCLES 25
+#endif
+#ifndef JOYSTICK_ADC_MAX
+#define JOYSTICK_ADC_MAX 0xFFFF
+#endif
+#define JOYSTICK_CENTER_DEADZONE JOYSTICK_ADC_MAX / 50
+
+struct JoystickValue
+{
+    JoystickValue()
+    : x(0)
+    , y(0)
+    {};
+    JoystickValue(int a)
+    : x(a)
+    , y(a)
+    {};
+    JoystickValue(int ax, int ay)
+    : x(ax)
+    , y(ay)
+    {};
+    int x;
+    int y;
+};
+
+class Joystick
+{
+public:
+    Joystick(PinName pinX, PinName pinY, void(*onChange)(JoystickValue value, JoystickValue prevValue) = NULL)
+    : _xIn(pinX)
+    , _yIn(pinY)
+    , _center(JOYSTICK_ADC_MAX / 2)
+    , _joyValue(0)
+    , _calibrated(false)
+    , _calibrationCounter(0)
+    , _range(JOYSTICK_ADC_MAX / 2)
+    , _swapXY(false)
+    , _flipX(false)
+    , _flipY(false)
+    , _delta(0)
+    , _onChange(onChange)
+    {};
+    void process();
+    void calibrate()
+    {
+        _center.x = JOYSTICK_ADC_MAX / 2;
+        _center.y = JOYSTICK_ADC_MAX / 2;
+        _calibrationCounter = 0;
+        _calibrated = false;
+    };
+    inline bool isCalibrated() const
+    {
+        return _calibrated;
+    };
+    inline bool isSwapXY() const
+    {
+        return _swapXY;
+    };
+    inline void setSwapXY(bool swapXY)
+    {
+        _swapXY = swapXY;
+    };
+    inline bool isFlipX() const
+    {
+        return _flipX;
+    };
+    inline void setFlipX(bool flipX)
+    {
+        _flipX = flipX;
+    };
+    inline bool isFlipY() const
+    {
+        return _flipY;
+    };
+    inline void setFlipY(bool flipY)
+    {
+        _flipY = flipY;
+    };
+    inline int getRange() const
+    {
+        return _range;
+    };
+    inline void setRange(int range)
+    {
+        _range = range;
+    };
+    inline int getDelta() const
+    {
+        return _delta;
+    };
+    inline void setDelta(int delta)
+    {
+        _delta = delta;
+    };
+    inline int getX() const
+    {
+        return _joyValue.x;
+    };
+    inline int getY() const
+    {
+        return _joyValue.y;
+    };
+    inline JoystickValue getCurrentValue() const
+    {
+        return _joyValue;
+    };
+private:
+    AnalogIn _xIn;
+    AnalogIn _yIn;
+    JoystickValue _center;
+    JoystickValue _joyValue;
+    bool _calibrated;
+    uint16_t _calibrationCounter;
+    int _range;
+    bool _swapXY;
+    bool _flipX;
+    bool _flipY;
+    int _delta;
+    void(*_onChange)(JoystickValue value, JoystickValue prevValue);
+};
+
+#endif //Joystick_h
+