/*
 * an arduino sketch to interface with a ps/2 keyboard.
 * Also uses serial protocol to talk back to the host
 * and report what it finds. Used the ps2 library.
 *
 * Taken from: http://www.arduino.cc/playground/ComponentLib/Ps2mouse
 * Written by Chris J. Kiick, January 2008.
 * modified for Smapler_v2 by Blushingboy
 *
 */

#include <ps2.h>

int leftPin = 3; // LED connected to digital pin 13
int rightPin = 11; // LED connected to digital pin 13 


/*
 * Pin 4 is the ps2 data pin, pin 2 is the clock pin
 * Feel free to use whatever pins are convenient.
 */

PS2 kbd(2, 4);

void playNote(int tone) { 

  for (int i=0; i < 100; 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
  }
} 


void kbd_init()
{
  char ack;

  kbd.write(0xff);  // send reset code
  ack = kbd.read();  // byte, kbd does self test
  ack = kbd.read();  // another ack when self test is done
}

void setup()
{
  pinMode(leftPin, OUTPUT);      // sets the digital pin as output
  pinMode(rightPin, OUTPUT);      // sets the digital pin as output
  Serial.begin(9600);
  kbd_init();
}

/*
 * get a keycode from the kbd and report it back to the
 * host via the serial line.
 */
void loop()
{
  unsigned char code;
  int count = 0;

  for (;;) { /* ever */

    /* read a keycode */
    code = kbd.read();
    count++;
    /* send the data back up */
    if (code != 0xF0 && count == 1) {
      if (code == 21) playNote(1911);
      else
        if (code == 29) playNote(1703);
        else
          if (code == 36) playNote(1517);
          else
            if (code == 45) playNote(1432);
            else
              if (code == 44) playNote(1276);
              else
                if (code == 53) playNote(1136);
                else
                  if (code == 60) playNote(1012);
                  else 
                    if (code == 67) playNote(956);


      Serial.println(code, DEC);
    }
    if (count == 3) count = 0;
    //delay(20);  /* twiddle */
  }
}