Skip to content

Instantly share code, notes, and snippets.

@Charl13
Last active June 17, 2021 20:21
Show Gist options
  • Save Charl13/257c4297f38cc06e95a4f59c3490e3fc to your computer and use it in GitHub Desktop.
Save Charl13/257c4297f38cc06e95a4f59c3490e3fc to your computer and use it in GitHub Desktop.
Draft: Arduino MPU6050 via I2C
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
MPU6050 mpu;
#define INTERRUPT_PIN 7
bool dmpReady = false; // set true if DMP init was successful
uint8_t devStatus; // return status after each device operation (0 = success, !0 = error)
uint8_t fifoBuffer[64]; // FIFO storage buffer
Quaternion q; // [w, x, y, z] quaternion container
VectorFloat gravity; // [x, y, z] gravity vector
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void setup() {
Wire.begin();
Wire.setClock(400000);
Serial.begin(115200);
while (!Serial);
setupMpu6050();
}
void loop() {
if (!dmpReady) return;
if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) {
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
//Serial.print("ypr\t");
//Serial.print(ypr[0] * 180/M_PI);
//Serial.print("\t");
Serial.println(ypr[1] * 180/M_PI);
//Serial.print("\t");
//Serial.println(ypr[2] * 180/M_PI);
}
delay(100);
}
bool setupMpu6050() {
pinMode(INTERRUPT_PIN, INPUT);
mpu.initialize();
Serial.println(F("Testing device connections..."));
Serial.println(
mpu.testConnection()
? F("MPU6050 connection successful")
: F("MPU6050 connection failed")
);
if (mpu.dmpInitialize() == 0) {
mpu.CalibrateAccel(6);
mpu.CalibrateGyro(6);
mpu.PrintActiveOffsets();
dmpReady = true;
} else {
Serial.print(F("DMP Initialization failed (code "));
Serial.print(devStatus);
Serial.println(F(")"));
}
Serial.println(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
return true;
}
void dmpDataReady() {
mpuInterrupt = true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment