wobblyhead hg > arduino > Joystick
view Joystick.cpp @ 5:328b2e0c7555
//debug
| author | ark |
|---|---|
| date | 2017-02-05 16:19 +0100 |
| parents | d423ea399401 |
| children |
line wrap: on
line source
#if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "Joystick.h" //#define DEBUG /** see Joystick.h for description. */ Joystick::Joystick() {} /** setup joystick instance @param {byte} pinX input pin for x axis @param {byte} pinY input pin for y axis @param {byte} pinB input pin for button */ void Joystick::setup(byte pinX, byte pinY, byte pinB) { setup(pinX, pinY, pinB, true); } /** setup joystick instance @param {byte} pinX input pin for x axis @param {byte} pinY input pin for y axis @param {byte} pinB input pin for button @param {bool} flipY mirror y axis output */ void Joystick::setup(byte pinX, byte pinY, byte pinB, bool flipY) { x.setup(pinX); y.setup(pinY); b.setup(pinB, true); centerX = 512; centerY = 512; this->flipY = flipY; } void Joystick::update() { update(millis()); } void Joystick::update(unsigned long ms) { x.update(ms); y.update(ms); b.update(ms); // if not calibrated yet, and stick is stopped within the center deadzone, // auto-calibrate to that point if(!isCalibrated) { isCentered = abs(512-x.value) < CENTER_DEADZONE_UNCALIBRATED && abs(512-y.value) < CENTER_DEADZONE_UNCALIBRATED; if(isCentered) { if(x.isStopped && y.isStopped) { isCalibrated = true; centerX = x.value; centerY = y.value; #ifdef DEBUG Serial.print(ms); Serial.print(": Joystick calibrated, center="); Serial.print(centerX); Serial.print(","); Serial.println(centerY); #endif } else return; } } // raw values deltas from (calibrated or assumed) center float dx = x.value-centerX; float dy = y.value-centerY; // if calibrated, check here if centered if(isCalibrated) isCentered = abs(dx) < CENTER_DEADZONE_CALIBRATED && abs(dy) < CENTER_DEADZONE_CALIBRATED; // if centered, reduce vector to 0,0 if(isCentered) { vx = 0.0; vy = 0.0; } else { // calculate vector mapping 0..centerN..1023 to -100..0..100 if(dx < 0) vx = dx*100/centerX; else vx = dx*100/(1023-centerX); if(dy < 0) vy = dy*100/centerY; else vy = dy*100/(1023-centerY); // flip vy to cartesian logic if configured if(this->flipY) vy = -vy; } // add digital vector dvx = vx < -CENTER_RADIUS_DIGITAL ? -100 : vx > CENTER_RADIUS_DIGITAL ? 100 : 0; dvy = vy < -CENTER_RADIUS_DIGITAL ? -100 : vy > CENTER_RADIUS_DIGITAL ? 100 : 0; }
