#include <Wire.h>
#include <MPU6050.h>
// Pin configuration
const int buzzerPin = 3; // Pin untuk buzzer
const int nearLedPin = 12; // Pin untuk LED
// MPU6050 object
MPU6050 mpu;
void setup() {
pinMode(buzzerPin, OUTPUT); // Buzzer
pinMode(nearLedPin, OUTPUT); // LED
Serial.begin(9600); // Serial monitor
// Initialize MPU6050
Wire.begin();
mpu.initialize();
// Check if MPU6050 is connected
if (!mpu.testConnection()) {
Serial.println("MPU6050 connection failed!");
while (1);
}
}
void loop() {
// Variables to hold accelerometer data
int16_t ax, ay, az;
// Read accelerometer data
mpu.getAcceleration(&ax, &ay, &az);
// Calculate the roll and pitch angles from accelerometer data
float roll = atan2(ay, az) * 180.0 / PI;
float pitch = atan2(ax, sqrt(ay * ay + az * az)) * 180.0 / PI;
// Print the pitch and roll angles to Serial Monitor
Serial.print("Pitch: ");
Serial.print(pitch);
Serial.print(" | Roll: ");
Serial.println(roll);
// Check if pitch or roll angle exceeds 15 degrees
if (abs(pitch) > 15 || abs(roll) > 15) {
tone(buzzerPin, 1000); // Bunyikan buzzer
digitalWrite(nearLedPin, HIGH); // Nyalakan LED
} else {
noTone(buzzerPin); // Matikan buzzer
digitalWrite(nearLedPin, LOW); // Matikan LED
}
delay(100); // Delay to prevent overwhelming the serial output
}