Lesson 12: Joystick Control

Two-axis analog input driving the robot arm's base and shoulder servos

đŸ•šī¸ Push the stick a little for slow motion — push it far for fast motion

đŸŽ¯ Learning Objectives

By the end of this lesson, you will:

  • Wire a two-axis joystick module and read it with analogRead()
  • Measure your joystick's real resting center and build a dead zone around it
  • Make servo speed proportional to how far the stick is pushed
  • Drive two servos at once with non-blocking millis() timing

Key Concepts:

  • Analog input calibration and center offset
  • Dead zones (ignoring small, noisy inputs)
  • Rate control — deflection maps to step size
  • Incremental servo movement with timed updates

đŸ“Ļ Section 1: Parts Inventory

New this lesson

  • 1 × two-axis joystick module (KY-023 style, with pushbutton)
  • 5 × male-to-female jumper wires for the joystick header

Carried over from Lesson 11

  • Arduino Uno + USB cable
  • 2 × SG90 servos (base + shoulder)
  • Breadboard and jumper wires
  • Optional: piezo buzzer, pushbutton

📌 Section 2: Pin Map & Wiring

The joystick module has five pins: GND, +5V, VRx (X-axis voltage), VRy (Y-axis voltage), and SW (the click button inside the stick).

Same robot-arm pin map, with the joystick added

  • Joystick VRx: A0 (left/right → base servo)
  • Joystick VRy: A1 (up/down → shoulder servo)
  • Joystick SW: D2 (to GND when pressed, INPUT_PULLUP)
  • Joystick +5V / GND: power rail / ground rail
  • Button: A2 (unchanged from Lesson 11)
  • Buzzer (optional): pin 8
  • Base servo signal: pin 9
  • Shoulder servo signal: pin 10

Wiring Diagram

Fritzing breadboard diagram: Arduino Uno wired to a 5-pin analog joystick (VRx to A0, VRy to A1, SW to D2, powered from 5V and GND) and two SG90 servos (signal wires to pins 9 and 10, power and ground on the breadboard rails)

Reading the diagram: the joystick's five pins land as GND → ground rail, +5V → power rail, VRx (blue) → A0, VRy (green) → A1, SW (orange) → D2. Each servo's yellow wire is its signal (pins 9 and 10); red and black feed the breadboard power rails.

The Real Thing

Photo of the actual robot arm wiring: Elegoo Uno board on the left connected to a breadboard, the 5-pin joystick module at bottom right, and the white robot arm base with servos at top — jumper wires running between all of them

Diagram vs. desk: same connections, real hardware. Compare this photo to the diagram above — the joystick sits on the arm's control panel, the servo cables run down to the breadboard rails, and the Uno ties it all together. Your wiring doesn't need to look identical; it needs to match electrically.

âš ī¸ Power reminder

The joystick itself uses almost no current — it can share the Arduino 5V rail safely. The servos are still the power-hungry part: if they jitter, feed them from an external 5V supply and keep all grounds tied together.

đŸ•šī¸ Section 3: How the Joystick Works

A two-axis joystick is really two potentiometers in one package, plus a pushbutton when you press the stick straight down. You already know how to read a potentiometer — analogRead() returns a value from 0 to 1023:

  • Stick pushed fully one way → reading near 0
  • Stick resting in the middle → reading near 512
  • Stick pushed fully the other way → reading near 1023

"Near 512" is doing a lot of work in that sentence — real joysticks rarely rest at exactly 512, and the value jitters by a few counts even when nobody is touching the stick. Sections 4 and 5 deal with that.

📟 Section 4: Reading Raw Values

First, prove the wiring works. This tiny sketch prints both axes to Serial Monitor — no servos needed yet:

// Joystick raw value reader
const int joyX = A0;
const int joyY = A1;

void setup() {
    Serial.begin(9600);
}

void loop() {
    int x = analogRead(joyX);
    int y = analogRead(joyY);

    Serial.print("X: ");
    Serial.print(x);
    Serial.print("   Y: ");
    Serial.println(y);

    delay(150);   // slow the stream down so humans can read it
}

đŸ”Ŧ Try it

Upload it, open Serial Monitor, and don't touch the stick. Write down the resting X and Y values — that's your joystick's real center. Now push full-left, full-right, full-up, full-down and note which axis changes and in which direction. Every module is a little different.

📍 Section 5: Calibration and the Dead Zone

Two problems to solve before driving servos. First, your stick's center might be 503 or 521 — not 512. So we calibrate in setup(): average a bunch of readings while the stick rests, and remember that as the true center:

int centerX = 512;
int centerY = 512;
const int deadZone = 25;    // ignore wiggles smaller than this

void calibrateJoystick() {
    long sumX = 0, sumY = 0;
    Serial.println("Calibrating - hands off the stick!");
    for (int i = 0; i < 50; i++) {
        sumX += analogRead(joyX);
        sumY += analogRead(joyY);
        delay(10);
    }
    centerX = sumX / 50;    // true resting center
    centerY = sumY / 50;
}

Second, even a resting stick wobbles by Âą10 counts or so. The dead zone says: if the stick is within 25 counts of center, treat it as centered. Without it, your servos would creep and jitter on their own.

deflection = reading - center

|deflection| <  deadZone   →   stick counts as centered (do nothing)
|deflection| >= deadZone   →   real input (move, and move faster if far)

đŸĸ🐇 Section 6: Speed Follows the Stick

In Lesson 11, every timed step moved exactly 1°. For joystick control that feels wrong — a small push should creep, a big push should zip. The trick: keep the timing fixed, and scale the step size with deflection:

small deflection (just past dead zone)  →  1° per step  →  slow creep
large deflection (stick slammed over)  →  4° per step  →  fast move
const int maxStep = 4;   // degrees per step at full deflection

int signOf(int v) {
    return (v > 0) - (v < 0);   // +1, -1, or 0
}

// How many degrees to move this step, given the stick deflection
int stepFor(int deflection) {
    int d = abs(deflection);
    if (d < deadZone) return 0;                    // inside dead zone: hold still
    return map(d, deadZone, 512, 1, maxStep);      // scale 1..4 degrees
}

signOf(deflection) picks the direction, stepFor(deflection) picks how much. Multiply them and you get a signed step — the rest is the same timed-update pattern from Lesson 11.

🧩 Section 7: The Complete Sketch

Everything together: the joystick drives X → base and Y → shoulder, clicking the stick sends both servos home to 90°, and all motion uses the non-blocking timed step:

// ============================================================
// Lesson 12: Joystick Control
// Two-axis joystick driving two SG90 servos:
//   X axis -> base rotation (pin 9)
//   Y axis -> shoulder      (pin 10)
//   SW (stick click) -> both servos return home to 90
// Features: startup calibration, dead zone, speed that scales
// with deflection, non-blocking millis() motion.
// ============================================================

#include <Servo.h>

Servo baseServo;
Servo shoulderServo;

// ---- Pins ----
const int joyX  = A0;
const int joyY  = A1;
const int joySW = 2;     // stick click button on D2 (INPUT_PULLUP)

// ---- Servo angles ----
int baseAngle     = 90;
int shoulderAngle = 90;
const int MIN_ANGLE = 20;
const int MAX_ANGLE = 160;

// ---- Joystick calibration ----
int centerX = 512;
int centerY = 512;
const int deadZone = 25;

// ---- Motion timing ----
unsigned long lastStepTime = 0;
const int stepInterval = 15;   // ms between motion steps
const int maxStep = 4;         // degrees per step at full deflection

// ---- Stick button state ----
int lastSWState = HIGH;

int signOf(int v) {
    return (v > 0) - (v < 0);            // +1, -1, or 0
}

// How many degrees to move this step, given stick deflection
int stepFor(int deflection) {
    int d = abs(deflection);
    if (d < deadZone) return 0;                  // ignore tiny wiggles
    return map(d, deadZone, 512, 1, maxStep);    // 1..4 degrees
}

// Measure the true resting center at startup
void calibrateJoystick() {
    long sumX = 0, sumY = 0;
    Serial.println("Calibrating - hands off the stick!");
    for (int i = 0; i < 50; i++) {
        sumX += analogRead(joyX);
        sumY += analogRead(joyY);
        delay(10);
    }
    centerX = sumX / 50;
    centerY = sumY / 50;
    Serial.print("Center X: "); Serial.print(centerX);
    Serial.print("   Center Y: "); Serial.println(centerY);
}

void setup() {
    Serial.begin(9600);
    baseServo.attach(9);
    shoulderServo.attach(10);
    pinMode(joySW, INPUT_PULLUP);
    baseServo.write(baseAngle);
    shoulderServo.write(shoulderAngle);
    calibrateJoystick();
    Serial.println("Joystick control ready. Click stick = HOME.");
}

void loop() {
    // 1. Timed motion step (non-blocking)
    if (millis() - lastStepTime >= stepInterval) {
        lastStepTime = millis();

        int dx = analogRead(joyX) - centerX;   // deflection from center
        int dy = analogRead(joyY) - centerY;

        baseAngle     = constrain(baseAngle     + signOf(dx) * stepFor(dx), MIN_ANGLE, MAX_ANGLE);
        shoulderAngle = constrain(shoulderAngle + signOf(dy) * stepFor(dy), MIN_ANGLE, MAX_ANGLE);

        baseServo.write(baseAngle);
        shoulderServo.write(shoulderAngle);
    }

    // 2. Stick click -> return home
    int swState = digitalRead(joySW);
    if (swState == LOW && lastSWState == HIGH) {
        baseAngle = 90;
        shoulderAngle = 90;
        Serial.println("HOME");
    }
    lastSWState = swState;
}

🔍 Notice the difference from Lesson 11

Last lesson, inputs set a target and the servos walked toward it. Here the stick is the motion command — no targets, just "keep stepping this direction at this speed while the stick is held." Both are the same timed-step engine; only the input changes.

🔧 Section 8: Tuning and Troubleshooting

Servo moves the wrong way

Your joystick may be mounted rotated relative to the arm. Flip the sign: use -dx or -dy in the angle update.

Servo drifts on its own

The dead zone is too small or calibration ran while the stick was touched. Raise deadZone to 35 and reset the board.

Too twitchy / too sluggish

Tune feel with maxStep (how fast full deflection is) and stepInterval (how often steps happen). Try maxStep 3 and interval 20.

Servo buzzes at the limits

You're pushing against MIN_ANGLE/MAX_ANGLE or the mechanical stop. Widen the code limits only if the hardware allows it.

đŸ› ī¸ Put It Together — Challenges

  • Swap the axes: make Y drive the base and X drive the shoulder. Which feels more natural to a pilot?
  • Add the elbow: bring back Lesson 11's poses on the A2 button — joystick for manual control, button cycles preset poses.
  • Reserve the click: right now SW goes home. Future robot-arm jobs for it: gripper open/close, or a mode toggle between manual and automatic.
  • Show your work: Serial-print base and shoulder angles once a second — you'll want them on a real display in Lesson 13.
Take Lesson 12 Quiz →
← Previous: Lesson 11
Course Overview
Next: Lesson 13 →