/********* Pleasedontcode.com **********

	Pleasedontcode thanks you for automatic code generation! Enjoy your code!

	- Terms and Conditions:
	You have a non-exclusive, revocable, worldwide, royalty-free license
	for personal and commercial use. Attribution is optional; modifications
	are allowed, but you're responsible for code maintenance. We're not
	liable for any loss or damage. For full terms,
	please visit pleasedontcode.com/termsandconditions.

	- Project: "MPU6050 Servo"
	- Source Code NOT compiled for: Arduino Nano
	- Source Code created on: 2024-07-09 00:13:52

********* Pleasedontcode.com **********/

/****** SYSTEM REQUIREMENTS *****/
/****** SYSTEM REQUIREMENT 1 *****/
	/* turn on the servo for 3 seconds when the mpu6050 */
	/* deflects by 40 degrees in either x axis or y axis */
	/* and shut it off when */
/****** SYSTEM REQUIREMENT 2 *****/
	/* When the MPU6050 detects a deflection of 40 */
	/* degrees or more on either the X or Y axis, */
	/* activate the servo motor connected to pin D5 for 3 */
	/* seconds, then turn it off. Use the MPU6050 */
	/* interrupt on pin D3 to trigger the action. */
/****** END SYSTEM REQUIREMENTS *****/

/****** DEFINITION OF LIBRARIES *****/
#include <Wire.h>
#include <MPU6050_6Axis_MotionApps20.h> //https://github.com/jrowberg/i2cdevlib
#include <Servo.h> // Include the Servo library

/****** FUNCTION PROTOTYPES *****/
void setup(void);
void loop(void);
void updateOutputs(void);
void dmpDataReady(void);

/***** DEFINITION OF DIGITAL INPUT PINS *****/
const uint8_t mpu_6050_MPU6050_Interrupt_PIN_D3 = 3;

/***** DEFINITION OF PWM OUTPUT PINS *****/
const uint8_t servo_Servomotor_PWMSignal_PIN_D5 = 5;

/***** DEFINITION OF I2C PINS *****/
const uint8_t mpu_6050_MPU6050_I2C_PIN_SDA_A4 = A4;
const uint8_t mpu_6050_MPU6050_I2C_PIN_SCL_A5 = A5;
const uint8_t mpu_6050_MPU6050_I2C_SLAVE_ADDRESS = 0x68; // MPU6050 I2C address

/***** DEFINITION OF OUTPUT RAW VARIABLES *****/
/***** used to store raw data *****/
uint8_t servo_Servomotor_PWMSignal_PIN_D5_rawData = 0;

/***** DEFINITION OF OUTPUT PHYSICAL VARIABLES *****/
/***** used to store data after characteristic curve transformation *****/
float servo_Servomotor_PWMSignal_PIN_D5_phyData = 0.0;

/****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
MPU6050 mpu(mpu_6050_MPU6050_I2C_SLAVE_ADDRESS); // Initialize MPU6050 object with I2C address
Servo myservo; // Initialize Servo object

/****** GLOBAL VARIABLES *****/
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
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 dmpDataReady() {
    mpuInterrupt = true;
}

void setup(void) {
    // put your setup code here, to run once:
    Wire.begin();
    Wire.setClock(400000); // 400kHz I2C clock

    Serial.begin(115200);
    while (!Serial);

    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(mpu_6050_MPU6050_Interrupt_PIN_D3, INPUT);

    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (!Serial.available());
    while (Serial.available() && Serial.read());

    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788);

    if (devStatus == 0) {
        mpu.CalibrateAccel(6);
        mpu.CalibrateGyro(6);
        mpu.PrintActiveOffsets();
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(mpu_6050_MPU6050_Interrupt_PIN_D3));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(mpu_6050_MPU6050_Interrupt_PIN_D3), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    pinMode(servo_Servomotor_PWMSignal_PIN_D5, OUTPUT);
    myservo.attach(servo_Servomotor_PWMSignal_PIN_D5); // Attach the servo to the PWM pin
}

void loop(void) {
    // put your main code here, to run repeatedly:
    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.print(ypr[1] * 180 / M_PI);
        Serial.print("\t");
        Serial.println(ypr[2] * 180 / M_PI);

        // Check if deflection is greater than 40 degrees on either X or Y axis
        if (abs(ypr[1] * 180 / M_PI) >= 40 || abs(ypr[2] * 180 / M_PI) >= 40) {
            myservo.write(90); // Activate the servo motor
            delay(3000); // Keep the servo on for 3 seconds
            myservo.write(0); // Deactivate the servo motor
        }
    }
}

void updateOutputs() {
    myservo.write(servo_Servomotor_PWMSignal_PIN_D5_rawData); // Write the mapped value to the servo
}

/* END CODE */