#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
const int ledPin = 15; // LED pin
const int tiltThresholdOn = 10; // Threshold angle for turning on the LED (in degrees)
const int tiltThresholdOff = -30; // Threshold angle for turning off the LED (in degrees)
void setup() {
Wire.begin();
Serial1.begin(115200);
Serial1.println("Initializing MPU6050...");
// Initialize MPU6050
mpu.initialize();
if (!mpu.testConnection()) {
Serial1.println("MPU6050 connection failed");
while (1); // Stop if the connection fails
}
Serial1.println("MPU6050 initialized successfully");
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Start with the LED off
}
void loop() {
int16_t ax, ay, az;
mpu.getAcceleration(&ax, &ay, &az);
// Calculate the tilt angle in the X direction
float xAngle = atan2(ax, sqrt(ay * ay + az * az)) * 180.0 / PI;
Serial1.print("Tilt Angle (X-axis): ");
Serial1.println(xAngle);
// Control the LED based on the tilt angle
if (xAngle > tiltThresholdOn) {
digitalWrite(ledPin, HIGH); // Turn the LED on when above 10 degrees
} else if (xAngle < tiltThresholdOff) {
digitalWrite(ledPin, LOW); // Turn the LED off when below -30 degrees
}
delay(100); // Short delay for responsiveness
}