PS/2 scroll mouse on an Arduino

By | 12th August 2017

Quick example how to read the PS/2 scroll wheel from an Arduino. Based on information from here.

#include "ps2.h"

unsigned char ps2mousetype = 0;
static const int kPin_ClockPS2 = 8;
static const int kPin_DataPS2 = 7;

PS2 mouseps2(kPin_ClockPS2, kPin_DataPS2);

void setup()
{
  Serial.begin(9600);
  mouseps2.write(0xff);   // reset
  mouseps2.read();        // ack byte [FA]
  mouseps2.read();        // blank    [AA]
  mouseps2.read();        // blank    [00]

  mouseps2.write(0xf0);   // remote mode
  mouseps2.read();        // ack      [FA]

  // Enable mouse wheel
  mouseps2.write(0xf3);                   // Set Sample Rate 200
  mouseps2.read();        // ack
  mouseps2.write(200);
  mouseps2.read(), HEX);  // ack

  mouseps2.write(0xf3);                   // Set Sample Rate 100
  mouseps2.read();        // ack
  mouseps2.write(100);
  mouseps2.read();        // ack

  mouseps2.write(0xf3);                   // Set Sample Rate 80
  mouseps2.read();        // ack
  mouseps2.write(80);
  mouseps2.read();        // ack

  // Read Device ID
  // Response 03 if microsoft scrolling mouse.
  // Response 04 if 5-button scrolling mouse.
  mouseps2.write(0xF2);                   // Get device ID
  mouseps2.read();
  ps2mousetype = mouseps2.read();

  delayMicroseconds(100);
}

void loop()
{
  // get a reading from the mouse
  mouseps2.write(0xEB);
  mouseps2.read(); // ack

  unsigned char uData = mouseps2.read(); // bit pattern of buttons pressed and other things
  Serial.print(uData, HEX);
  Serial.print(" ");
  unsigned char uX = mouseps2.read();    // signed twos-complement of the X movement
  Serial.print(uX, HEX);
  Serial.print(" ");
  unsigned char uY = mouseps2.read();    // ditto, for y
  Serial.print(uY, HEX);
  Serial.print(" ");

  if (ps2mousetype > 0)
  {
    // Read the mouse wheel.  01=Up FF=Down
    unsigned char wheel = mouseps2.read();
    Serial.print(wheel, HEX);
  }
  Serial.println();
}

Leave a Reply

Your email address will not be published. Required fields are marked *