#include <Keyboard.h>

const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 8; // LED connected to pin 8
const int irPin = 7; // IR sensor connected to pin 7
const int detectionThreshold = 50; // Detection threshold distance in cm

bool isWPressed = false; // Variable to keep track of the 'w' key state

void setup() {
  // Initialize the serial communication:
  Serial.begin(9600);
  
  // Initialize the ultrasonic sensor pins:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Initialize the LED pin:
  pinMode(ledPin, OUTPUT);
  
  // Initialize the IR sensor pin:
  pinMode(irPin, INPUT);
  
  // Initialize the Keyboard:
  Keyboard.begin();
}

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  
  // Trigger the sensor by setting the trigPin HIGH for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  long duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance:
  int distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  
  // Print the distance to the Serial Monitor (optional):
  Serial.print("Distance: ");
  Serial.println(distance);
  
  // Check if the distance is greater than the threshold:
  if (distance > detectionThreshold) {
    // Send a SPACE keystroke:
    Keyboard.press(' ');
    delay(100); // Small delay to avoid multiple detections
    Keyboard.release(' ');
    
    // Turn on the LED:
    digitalWrite(ledPin, HIGH);
  } else {
    // Turn off the LED if an object is detected:
    digitalWrite(ledPin, LOW);
  }
  
  // Read the IR sensor:
  int irState = digitalRead(irPin);
  
  // If the IR sensor detects something (assuming LOW means detection):
  if (irState == LOW) {
    if (!isWPressed) {
      // Send a 'w' keystroke:
      Keyboard.press('w');
      isWPressed = true; // Update the state
    }
  } else {
    if (isWPressed) {
      // Release the 'w' keystroke:
      Keyboard.release('w');
      isWPressed = false; // Update the state
    }
  }
  
  // Wait for a short period before the next loop:
  delay(100);
}

void end() {
  // End the keyboard:
  Keyboard.end();
}

