#include <ps2.h>

#define LEDpin 9

/*
   an arduino sketch to interface with a ps/2 mouse.
   Also uses serial protocol to talk back to the host
   and report what it finds.
*/

/*
   Pin A1 is the mouse data pin, pin A0 is the clock pin
   Feel free to use whatever pins are convenient.
*/
PS2 mouse(A0, A1);

int a = 0, b = 0;
int aLast;
int p = 0;

char mstat;
char mx;
char my;

int m, x, y;
int mOld = 0;
/*
   initialize the mouse. Reset it, and place it into remote
   mode, so we can get the encoder data on demand.
*/
void mouse_init()
{
  mouse.write(0xff);  // reset
  mouse.read();  // ack byte
  mouse.read();  // blank */
  mouse.read();  // blank */
  mouse.write(0xf0);  // remote mode
  mouse.read();  // ack
  delayMicroseconds(100);
}

void mouseRead()
{
  /* get a reading from the mouse */
  mouse.write(0xeb);  // give me data!
  mouse.read();      // ignore ack
  mstat = mouse.read();
  mx = mouse.read();
  my = mouse.read();

  m = (int)mstat;
  x = (int)mx;
  y = (int)my;

  if (m == 8) {
    a = 1;
    b = 1;
  }
  else if (m == 9)
  {
    a = 0;
    b = 1;
  }
  else if (m == 10)
  {
    a = 1;
    b = 0;
  }
  else if (m == 11)
  {
    a = 0;
    b = 0;
  }

}

void setup()
{
  Serial.begin(9600);
  mouse_init();
}

/*
   get a reading from the mouse and report it back to the
   host via the serial line.
*/
void loop()
{

  mouseRead();

  

  if (a != aLast)
  {
    if (b != a && p < 255) p++;

    else if (p > 0) p--;
  }

  if (x > 1 && p < 255) p++;

  if (x < -1 && p > 0) p--;

  

  aLast = a;

  

  analogWrite(LEDpin, p);


  /* send the data back up */
  Serial.print(mstat, DEC);
  Serial.print("\tX=");
  Serial.print(x);
  Serial.print("\tY=");
  Serial.print(y);
  Serial.print("\tPos=");
  Serial.print(p);
  Serial.println();
  //delay(20);  /* twiddle */
}
