// Include the Wire library for I2C communication with MPU6050
#include <Wire.h>
// Include the Adafruit MPU6050 library
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
// Define the pin numbers for the PIR sensor, MPU6050, and LED
const int pirPin = 4; // PIR sensor input pin
const int ledPin = 13; // LED output pin
// Create an instance of the Adafruit MPU6050 class
Adafruit_MPU6050 mpu;
// Define a flag to track whether motion is detected by either sensor
bool motionDetected = false;
void setup() {
pinMode(pirPin, INPUT); // Set PIR sensor pin as input
pinMode(ledPin, OUTPUT); // Set LED pin as output
// Initialize the MPU6050
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
mpu.setAccelerometerRange(MPU6050_RANGE_2_G);
mpu.setGyroRange(MPU6050_RANGE_250_DEG);
}
void loop() {
// Read the state of the PIR sensor
int pirState = digitalRead(pirPin);
// Read accelerometer data
sensors_event_t accelEvent;
mpu.getAccelerometerSensor()->getEvent(&accelEvent);
// Read gyroscope data
sensors_event_t gyroEvent;
mpu.getGyroSensor()->getEvent(&gyroEvent);
// If motion is detected by either sensor, turn on the LED
if (pirState == HIGH || abs(accelEvent.acceleration.x) > 0.5 || abs(accelEvent.acceleration.y) > 0.5 || abs(accelEvent.acceleration.z) > 0.5 ||
abs(gyroEvent.gyro.x) > 1 || abs(gyroEvent.gyro.y) > 1 || abs(gyroEvent.gyro.z) > 1) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}