#include <Keyboard.h>

#define ECHOPIN 2// Pin to receive echo pulse
#define TRIGPIN 3// Pin to send trigger pulse


int location_thresh = 1;
int time_thresh = 2000; //no more than one hit per second
int  maxdist  = 250;

bool person_detected = false;
int old_dist = 0;
int last_hit_millis = 0;
void setup(){
  Keyboard.begin();
  Serial.begin(9600);
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  digitalWrite(ECHOPIN, HIGH);
}
void loop(){
  digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);
  digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW); // Send pin low again
  int distance = pulseIn(ECHOPIN, HIGH,26000); // Read in times pulse
  distance= distance/58;
  int datime = millis();
            Serial.print(distance);
          Serial.println("   cm");
  if (distance <= maxdist && distance > 0 && abs(last_hit_millis - datime) > time_thresh) {
    if (person_detected != true) {
        person_detected = true;
        last_hit_millis = millis();

          //Serial.print(distance);
         // Serial.println("   cm");
        //Serial.println("   yes");
        Keyboard.write(32);
    }
  }
  if (distance > maxdist && abs(old_dist - distance)>location_thresh ) {
    // Serial.print("UNDEETECTED");
    old_dist = distance;
    person_detected = false;
  }
  //Serial.print(distance);
  //Serial.println("   cm");
  delay(50);// Wait 50mS before next ranging
}
