#include <Wire.h>
/**
Define MPU-6050 address
*/
#define MPU_ADDR 0x68
void setup() {
// code to initialize the MPU-6050
Wire.begin();
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
// Baud-Rate = 9600 bit/s
Serial.begin(9600);
}
/**
Array to store 3-axis acc. values
*/
#define VALUES_SIZE 4
float rawValues [VALUES_SIZE];
/**
Define the sensitivity
*/
#define SENSITIVITY 16384
void loop() {
// code to start reading from the MPU-6050
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x3B);
Wire.endTransmission(false);
// IMPORTANT: The number of the requested bytes = # values * 2 = 4 * 2 = 8
Wire.requestFrom(MPU_ADDR, VALUES_SIZE * 2, true);
// read the raw values and store them in the array
for (int i = 0; i < VALUES_SIZE; i++) {
// each one is two successive 8-bit
rawValues[i] = Wire.read() << 8 | Wire.read();
}
// scale the raw values
float accX = rawValues[0] / SENSITIVITY;
float accY = rawValues[1] / SENSITIVITY;
float accZ = rawValues[2] / SENSITIVITY;
float temperature = (rawValues[3] / 340) + 36.53;
// print them on the serial monitor
Serial.print("X=");
Serial.print(accX);
Serial.print(" Y=");
Serial.print(accY);
Serial.print(" Z=");
Serial.print(accZ);
Serial.print(" Temperature=");
Serial.println(temperature);
// detect the tilting
if (accX > 0.5) {
Serial.println("Tilting to right!");
} else if (accX < -0.5) {
Serial.println("Tilting to left!");
}
if (accY > 0.5) {
Serial.println("Tilting to top!");
} else if (accY < -0.5) {
Serial.println("Tilting to bottom!");
}
delay(1000);
}