#include <Wire.h>
#include <MPU6050.h>
#include <HCSR04.h>
MPU6050 mpu;
const int trigPin = 8; // Trigger pin of HC-SR04
const int echoPin = 9; // Echo pin of HC-SR04
const int ledPin = 6; // LED connected to digital pin 13
long duration;
int distance;
int detectionRange = 200; // Define the detection range in centimeters
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pulse duration
duration = pulseIn(echoPin, HIGH);
// Convert the duration into distance
distance = duration * 0.034 / 2; // Speed of sound is 343 m/s (0.034 cm/us)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if an object is detected within the detection range
if (distance < detectionRange) {
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
delay(500); // Adjust the delay time as needed
}