#include <ps2.h>

/*
 * 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.
 *
 * Taken from: http://www.arduino.cc/playground/ComponentLib/Ps2mouse
 * Written by Chris J. Kiick, January 2008.
 * modified for Smapler_v2 by Blushingboy
 */

/*
 * Pin 2 is the mouse data pin, pin 4 is the clock pin
 * Feel free to use whatever pins are convenient.
 */
PS2 mouse(2, 4);

int leftPin = 3;
int rightPin = 11;

void playNote(int tone, int duration) { 

   for (int i=0; i < duration; i++) {
     digitalWrite(leftPin, HIGH);   // sets the LED on
     digitalWrite(rightPin, HIGH);   // sets the LED on
     delayMicroseconds(tone);                  // waits for a second
     digitalWrite(leftPin, LOW);    // sets the LED off
     delayMicroseconds(tone);                  // waits for a second
     digitalWrite(leftPin, HIGH);   // sets the LED on
     digitalWrite(rightPin, LOW);   // sets the LED on
     delayMicroseconds(tone);                  // waits for a second
     digitalWrite(leftPin, LOW);    // sets the LED off
     delayMicroseconds(tone);                  // waits for a second
   }
 } 



/*
 * 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 setup()
{
  pinMode(leftPin, OUTPUT);
  pinMode(rightPin, OUTPUT);
  Serial.begin(9600);
  mouse_init();
}

/*
 * get a reading from the mouse and report it back to the
 * host via the serial line.
 */
void loop()
{
  char mstat;
  char mx;
  char my;

  /* 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();

  /* send the data back up */
  Serial.print(mstat, BIN);
  Serial.print("\tX=");
  Serial.print(mx, DEC);
  Serial.print("\tY=");
  Serial.print(my, DEC);
  Serial.println();

  if (mx > 10 || mx < -10)
    playNote(10*abs(mx), abs(my));
//  delay(20);  /* twiddle */
}