#include <Arduino.h>
// Wire.h gives us I2C communication, used to talk to the motion sensor.
#include <Wire.h>

// 0x68 is the sensor I2C address for the reviewed MPU-6050 setup.
const uint8_t MPU_ADDRESS = 0x68;
// Use a true/false flag to remember whether initialization worked.
bool sensorReady = false;

// Open Serial, start I2C, and wake the sensor from sleep mode.
void setup() {
  Serial.begin(9600);
  Wire.begin();
  // Use a 100 kHz I2C clock for communication.
  Wire.setClock(100000);
  // Begin writing to the sensor at its I2C address.
  Wire.beginTransmission(MPU_ADDRESS);
  Wire.write(0x6B);  // PWR_MGMT_1: leave sleep mode.
  Wire.write(0);
  // A zero result means the I2C write was acknowledged.
  sensorReady = Wire.endTransmission() == 0;
}

// If the sensor responded, request a group of accelerometer and gyro values.
void loop() {
  // If initialization failed, report it and skip this reading.
  if (!sensorReady) {
    Serial.println("MPU-6050 not detected at 0x68");
    delay(1000);
    return;
  }
  Wire.beginTransmission(MPU_ADDRESS);
  // 0x3B points to the first measurement register; the next 14 bytes hold seven values.
  Wire.write(0x3B);  // ACCEL_XOUT_H; seven big-endian 16-bit values follow.
  // If the sensor does not respond or returns fewer bytes than expected, report an error.
  if (Wire.endTransmission(false) != 0 ||
      Wire.requestFrom(MPU_ADDRESS, uint8_t(14), uint8_t(true)) != 14) {
    Serial.println("Incomplete MPU-6050 read");
    delay(333);
    return;
  }
  // Store seven signed 16-bit readings: acceleration XYZ, temperature, and gyro XYZ.
  int16_t value[7];
  // Each reading is two bytes; combine high byte first because this sensor is big-endian.
  for (uint8_t i = 0; i < 7; ++i) {
    const uint16_t high = uint8_t(Wire.read());
    const uint16_t low = uint8_t(Wire.read());
    // << shifts the high byte left; | joins it with the low byte.
    value[i] = int16_t((high << 8) | low);
  }
  Serial.print("AcX="); Serial.print(value[0]);
  Serial.print(" | AcY="); Serial.print(value[1]);
  Serial.print(" | AcZ="); Serial.print(value[2]);
  // Convert the raw temperature value using the MPU-6050 formula.
  Serial.print(" | Tmp="); Serial.print(value[3] / 340.0 + 36.53);
  Serial.print(" | GyX="); Serial.print(value[4]);
  Serial.print(" | GyY="); Serial.print(value[5]);
  Serial.print(" | GyZ="); Serial.println(value[6]);
  delay(333);
}
