// Analog joystick with direction detection // XIAO RP2040 // VRX -> A0 // VRY -> A1 // VCC -> 3V3 // GND -> GND const int pinX = A0; const int pinY = A1; int centerX = 0; int centerY = 0; int deadZone = 200; // Dead zone to avoid noise around the center void setup() { Serial.begin(115200); delay(2000); // Do not touch the joystick during calibration // Automatic center calibration centerX = analogRead(pinX); centerY = analogRead(pinY); Serial.println("Calibrated center:"); Serial.print("X: "); Serial.println(centerX); Serial.print("Y: "); Serial.println(centerY); } void loop() { int xValue = analogRead(pinX); int yValue = analogRead(pinY); int stateX = 0; // -1 = LEFT, 0 = CENTER, 1 = RIGHT int stateY = 0; // -1 = DOWN, 0 = CENTER, 1 = UP // X axis detection if (xValue < centerX - deadZone) { stateX = -1; // LEFT } else if (xValue > centerX + deadZone) { stateX = 1; // RIGHT } // Y axis detection (inverted axis) if (yValue < centerY - deadZone) { stateY = 1; // UP } else if (yValue > centerY + deadZone) { stateY = -1; // DOWN } // Serial Monitor output Serial.print("X: "); Serial.print(xValue); Serial.print(" | Y: "); Serial.print(yValue); Serial.print(" | PosX: "); if (stateX == -1) Serial.print("LEFT"); else if (stateX == 1) Serial.print("RIGHT"); else Serial.print("CENTER"); Serial.print(" | PosY: "); if (stateY == -1) Serial.print("DOWN"); else if (stateY == 1) Serial.print("UP"); else Serial.print("CENTER"); Serial.println(); delay(100); }