I put together a small Arduino sketch that reads movement from a PS/2 optical mouse and converts it to distance. It reports net X/Y displacement and total path length in cm.
How it works:
- Reads the dx/dy counts from the mouse each loop
- Converts counts to cm using the sensor’s CPI
- You calibrate by sliding the mouse exactly 10 cm and adjusting
COUNTS_PER_INCH - Calibration note: the 400 CPI value in the sketch is only a starting guess. Note that a PS/2 mouse’s reported counts may not match the sensor’s rated CPI, so treat any spec lookup (e.g. mousedpianalyzers.com) as a rough starting point, then fine-tune with the 10 cm slide test.
I have not tested this on hardware yet, so I would like feedback on:
- Whether the PS2Mouse library calls are correct
- How much drift or error to expect over longer distances, and on which surfaces
- Whether a dedicated optical flow sensor would be a better choice for this
Code is below. /*
Mouse Distance Tracker (PS/2 optical mouse + Arduino)
Status: UNTESTED DRAFT. Check the PS2Mouse library examples for the exact API.
Wiring (5 V Arduino, PS/2 mouse):
Mouse CLOCK → pin 6
Mouse DATA → pin 5
Mouse VCC → 5 V, GND → GND
Library: “PS2Mouse” (install via Library Manager or GitHub)
Calibration: slide the mouse exactly 10 cm along one axis, read the counts
printed on Serial, then set COUNTS_PER_INCH = counts / 10.0 * 2.54
*/
#include <PS2Mouse.h>
const int CLOCK_PIN = 6;
const int DATA_PIN = 5;
// Starting guess for a typical 400 CPI mouse; replace after calibrating.
float COUNTS_PER_INCH = 400.0;
PS2Mouse mouse(CLOCK_PIN, DATA_PIN);
long netX = 0; // net displacement in counts
long netY = 0;
float pathCounts = 0.0; // total path length in counts
void setup() {
Serial.begin(115200);
mouse.initialize();
Serial.println(“Mouse distance tracker ready. Send ‘r’ to reset.”);
}
void loop() {
if (Serial.available() && Serial.read() == ‘r’) {
netX = 0; netY = 0; pathCounts = 0;
Serial.println(“Reset.”);
}
MouseData data = mouse.readData();
int dx = data.position.x;
int dy = data.position.y;
if (dx != 0 || dy != 0) {
netX += dx;
netY += dy;
pathCounts += sqrt((float)dx * dx + (float)dy * dy);
float cmPerCount = 2.54 / COUNTS_PER_INCH;
Serial.print("Net X cm: "); Serial.print(netX * cmPerCount, 2);
Serial.print(" Net Y cm: "); Serial.print(netY * cmPerCount, 2);
Serial.print(" Path cm: "); Serial.println(pathCounts * cmPerCount, 2);
}
delay(10);
}