The first thing we need is to install the library to allow us to read the accelerometer over I2C. If you have never installed a library, you can watch this video that shows you how. This time the library we're looking for is "MPU6050_tockn". which looks like this in the Library Manager:
Just search for "MPU6050" and scroll down until you see, "MPU6050_tockn". (Note there are plenty of other libraries that read this chip. You might want to try some of the others as well to see what each one offers.) Finally, click the Install button.
Wiring the accelerometer only requires four quick connections. The only challenge is that currently, the SDA pin on the Renton Leonardo boards doesn't seem to be working, but this isn't a problem
Accel. VCC pin --> 5V/VCC (Red pin on Arduino)
Accel. GND pin --> GND (Black pin on Arduino)
Accel. SCL pin --> D3 (Yellow pin on Arduino)
Accel. SDA pin --> D2 (Yellow pin on Arduino)
Note: If the SDA and SCL pins are already occupied, you'll need to use a Breadboard.
#include <MPU6050_tockn.h>
#include <Wire.h>
MPU6050 mpu6050(Wire);
long timer = 0;
void setup() {
Serial.begin(9600);
Wire.begin();
mpu6050.begin();
mpu6050.calcGyroOffsets(true);
}
void loop() {
mpu6050.update();
if(millis() - timer > 1000){
Serial.println("=======================================================");
Serial.print("temp : ");Serial.println(mpu6050.getTemp());
Serial.print("accX : ");Serial.print(mpu6050.getAccX());
Serial.print("\taccY : ");Serial.print(mpu6050.getAccY());
Serial.print("\taccZ : ");Serial.println(mpu6050.getAccZ());
Serial.print("gyroX : ");Serial.print(mpu6050.getGyroX());
Serial.print("\tgyroY : ");Serial.print(mpu6050.getGyroY());
Serial.print("\tgyroZ : ");Serial.println(mpu6050.getGyroZ());
Serial.print("accAngleX : ");Serial.print(mpu6050.getAccAngleX());
Serial.print("\taccAngleY : ");Serial.println(mpu6050.getAccAngleY());
Serial.print("gyroAngleX : ");Serial.print(mpu6050.getGyroAngleX());
Serial.print("\tgyroAngleY : ");Serial.print(mpu6050.getGyroAngleY());
Serial.print("\tgyroAngleZ : ");Serial.println(mpu6050.getGyroAngleZ());
Serial.print("angleX : ");Serial.print(mpu6050.getAngleX());
Serial.print("\tangleY : ");Serial.print(mpu6050.getAngleY());
Serial.print("\tangleZ : ");Serial.println(mpu6050.getAngleZ());
Serial.println("=======================================================\n");
timer = millis();
}
}