#include <Keyboard.h>
#include <Mouse.h>

/*
  These core libraries allow the 32u4 and SAMD based boards
  (Leonardo, Esplora, Zero, Due and MKR Family)
  to appear as a native Mouse and/or Keyboard to a connected computer.
*/

void setup() { // put your setup code here, to run once:
  Keyboard.begin(); // initialize control over the keyboard
  Keyboard.releaseAll();

  pinMode( 2 , INPUT);   // sets the digital pin as input
  Mouse.begin(); // initialize control over the mouse
}

void loop() { // put your main code here, to run repeatedly:
  if ( analogRead( A0 ) > 1016 ) {
    left();
    for (int i = 0 ; i < 500  ; ++i ) {
      left();
      delay( 1 ); // waits a few milliseconds
      left();
      if ( analogRead( A0 ) < 1016 ) {
        left();

        pinMode(4, INPUT_PULLUP); //make pin 4 an input and turn on the pullup resistor so it goes high unless connected to ground
        if (digitalRead(4) == LOW) { // do nothing until pin 4 goes low
          Keyboard.press('w'); //the key to press (ASCII code)
        }
      }
      left();
    }
    left();
  }
  else  {
    left();
    Keyboard.releaseAll();
    left();
  }
}

void left() { //customised function
  if (digitalRead( 2 )) {
    pinMode(4, INPUT_PULLUP); //make pin 4 an input and turn on the pullup resistor so it goes high unless connected to ground
    if (digitalRead(4) == LOW) { // do nothing until pin 4 goes low
      Mouse.click(MOUSE_LEFT);
    }
  }
}
