Stabilizer

Dependencies:   BEAR_Protocol mbed Stabilizer iSerial

Fork of MPU9250AHRS by BE@R lab

main.cpp

Committer:
soulx
Date:
2016-02-03
Revision:
21:298aa522db64
Parent:
15:10939fd0eaac
Parent:
20:1d4db25afe2b

File content as of revision 21:298aa522db64:


#include "Stabilizer.h"
#include "Kinematic.h"
#include "MPU9250.h"

#include "BEAR_Protocol.h"

void Init_IMU();
void Init_Stabilizer();
void WheelChair();


#define LEFT_SIDE 0x01
#define RIGHT_SIDE 0x02

#define TIME_SYNC_COMMUNICATION 5 //unit ms

float sum = 0;
uint32_t sumCount = 0;
char buffer[14];



//init class

MPU9250 mpu9250;
Stabilizer Stabilize(5.0f,0.0f);
//Kinematic L('Z',10,10,30,30),R('Z',10,10,30,30);
Kinematic Left(0,0),Right(0,0);
Bear_Communicate bcom(PA_15,PB_7,1000000);

Timer sync_communicate;


Timer t;

Serial pc(USBTX, USBRX); // tx, rx

Bear_Communicate bear(PA_15,PB_7,115200);



float xmax = -4914.0f;
float xmin = 4914.0f;

float ymax = -4914.0;
float ymin = 4914.0f;

float zmax = -4914.0;
float zmin = 4914.0f;

float Xsf,Ysf;
float Xoff,Yoff;


//InterruptIn event(PC_13);
DigitalIn enable(PC_13);

DigitalIn button(USER_BUTTON);

int16_t show_menu()
{
    int16_t option=9999;
    float temp[6];
    pc.printf("************Don't Forget to Save Data************\n");

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getMotorPos(LEFT_SIDE,&temp[0],&temp[1]);
    pc.printf("*\t1) Motor Left Hip [%f]\t\t*\n",temp[0]);
    pc.printf("*\t2) Motor Left Knee [%f]\t\t*\n",temp[1]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getMotorPos(RIGHT_SIDE,&temp[0],&temp[1]);
    pc.printf("*\t3) Motor Right Hip [%f]\t\t*\n",temp[0]);
    pc.printf("*\t4) Motor Right Knee [%f]\t\t*\n",temp[1]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getUpMotorKpKiKd(LEFT_SIDE,&temp[0],&temp[1],&temp[2]);
    pc.printf("*\t5) Kp : Left Hip [%f]\t\t*\n",temp[0]);
    pc.printf("*\t6) Ki : Left Hip [%f]\t\t*\n",temp[1]);
    pc.printf("*\t7) Kd : Left Hip [%f]\t\t*\n",temp[2]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getLowMotorKpKiKd(LEFT_SIDE,&temp[0],&temp[1],&temp[2]);
    pc.printf("*\t8) Kp : Left Knee [%f]\t\t*\n",temp[0]);
    pc.printf("*\t9) Ki : Left Knee [%f]\t\t*\n",temp[1]);
    pc.printf("*\t10) Kd : Left Knee [%f]\t\t*\n",temp[2]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getUpMotorKpKiKd(RIGHT_SIDE,&temp[0],&temp[1],&temp[2]);
    pc.printf("*\t11) Kp : Right Hip [%f]\t\t*\n",temp[0]);
    pc.printf("*\t12) Ki : Right Hip [%f]\t\t*\n",temp[1]);
    pc.printf("*\t13) Kd : Right Hip [%f]\t\t*\n",temp[2]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getLowMotorKpKiKd(RIGHT_SIDE,&temp[0],&temp[1],&temp[2]);
    pc.printf("*\t14) Kp : Right Knee [%f]\t\t*\n",temp[0]);
    pc.printf("*\t15) Ki : Right Knee [%f]\t\t*\n",temp[1]);
    pc.printf("*\t16) Kd : Right Knee [%f]\t\t*\n",temp[2]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getUpMargin(LEFT_SIDE,&temp[0]);
    pc.printf("*\t17) Set Left Hip Margin [%f]\n",temp[0]);
    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getLowMargin(LEFT_SIDE,&temp[0]);
    pc.printf("*\t18) Set Left Knee Margin [%f]\n",temp[0]);
    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getUpMargin(RIGHT_SIDE,&temp[0]);
    pc.printf("*\t19) Set Right Hip Margin [%f]\n",temp[0]);
    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getLowMargin(RIGHT_SIDE,&temp[0]);
    pc.printf("*\t20) Set Right Knee Margin [%f]\n",temp[0]);


    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getUpLinkLength(LEFT_SIDE,&temp[0]);
    pc.printf("*\t21) Set Lenght of Left Link Hip [%f]\n",temp[0]);
    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getLowLinkLength(LEFT_SIDE,&temp[0]);
    pc.printf("*\t22) Set Lenght of Left Link Knee [%f]\n",temp[0]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getUpLinkLength(RIGHT_SIDE,&temp[0]);
    pc.printf("*\t23) Set Lenght of Right Link Hip [%f]\n",temp[0]);
    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getLowLinkLength(RIGHT_SIDE,&temp[0]);
    pc.printf("*\t24) Set Lenght of Right Link Knee [%f]\n",temp[0]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getOffset(LEFT_SIDE,&temp[0],&temp[1]);
    pc.printf("*\t25) Set Offset x[%f] y[%f]\n",temp[0],temp[1]);
    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getBodyWidth(LEFT_SIDE,&temp[0]);
    pc.printf("*\t26) Set Body Width [%f]\n",temp[0]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getUpAngleRange(LEFT_SIDE,&temp[0],&temp[1]);
    bcom.getUpAngleRange(RIGHT_SIDE,&temp[2],&temp[3]);
    pc.printf("*\t27) Set Maximum Hip Angle Range \n");
    pc.printf("\tLeft Maximum Hip Angle Range [%f]\n",temp[0]);
    pc.printf("\tRight Maximum Hip Angle Range [%f]\n\n",temp[2]);

    pc.printf("*\t28) Set Minimum Hip Angle Range \n");
    pc.printf("\tLeft Minimum Hip Angle Range [%f]\n",temp[1]);
    pc.printf("\tRight Minimum Hip Angle Range [%f]\n\n",temp[3]);

    while(sync_communicate.read_ms() < TIME_SYNC_COMMUNICATION);
    sync_communicate.reset();
    bcom.getLowAngleRange(LEFT_SIDE,&temp[0],&temp[1]);
    bcom.getLowAngleRange(RIGHT_SIDE,&temp[2],&temp[3]);
    pc.printf("*\t29) Set Maximum Knee Angle Range \n");
    pc.printf("\tLeft Maximum Knee Angle Range [%f]\n",temp[0]);
    pc.printf("\tRight Maximum Knee Angle Range [%f]\n\n",temp[2]);

    pc.printf("*\t30) Set Minimum Knee Angle Range \n");
    pc.printf("\tLeft Minimum Knee Angle Range [%f]\n",temp[1]);
    pc.printf("\tRight Minimum Knee Angle Range [%f]\n\n",temp[3]);

    pc.printf("*\t40) Exit Program \t\t\t*\n");
    pc.printf("************Don't Forget to Save Data************\n");
    // Prompting user to enter an option according to menu
    pc.printf("Please select an option : ");


    pc.scanf("%d",&option);
    if(sync_communicate.read_ms() >0x7FFFFF00) {
        sync_communicate.reset();
    }
    pc.printf("\n");



    return option;
}

void SwMode()
{
    int option;
    float temp;
    float LH,LK,RH,RK;
    //float LLink[2],RLink[2];
    float LLink0=21.5,LLink1=27.0,RLink0=22.5,RLink1=27.0;
    struct max_ang {
        float Hip;
        float Knee;
    };
    struct min_ang {
        float Hip;
        float Knee;
    };
    max_ang Lmax,Lmin;
    min_ang Rmax,Rmin;
    Lmax.Knee = Lmax.Hip = Lmin.Knee = Lmin.Hip = Rmax.Knee = Rmax.Hip = Rmin.Knee = Rmin.Hip = 0;
    bool a,b,c,d;
    a = b = c = d = false;


    float temp_LH=0,temp_LK=0,temp_RH=0,temp_RK=0;

    bcom.getMotorPos(LEFT_SIDE,&temp_LH,&temp_LK);
    bcom.getMotorPos(RIGHT_SIDE,&temp_RH,&temp_RK);

    do {
        //float buff;

        option = show_menu();


        if(option == 1)// Left Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                //Send Position to Motor
                pc.printf("Input Degree : \n");
                pc.scanf("%f",&temp);
                if(temp!=9999) {
                    LH = temp;
                    pc.printf("Move Left Hip Motor to %f Degree\n",LH);

                    bcom.setMotorPos(LEFT_SIDE,LH,temp_LK);
                    temp_LH = LH;

                    /********************Save Data*********************/
                } //else bcom.saveDataToEEPROM(LEFT_SIDE,MOTOR_UPPER_ANG);

            } while(temp != 9999);

        else if(option == 2) //Left Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");

                //Send Position to Motor
                pc.printf("Input Degree : \n");
                pc.scanf("%f",&temp);
                if(temp!=9999) {
                    LK = temp;
                    pc.printf("Move Left Knee Motor to %f Degree\n",LK);

                    bcom.setMotorPos(LEFT_SIDE,temp_LH,LK);
                    temp_LK = LK;


                    /********************Save Data*********************/
                } //else bcom.saveDataToEEPROM(LEFT_SIDE,MOTOR_LOWER_ANG);

            } while(temp != 9999);


        else if(option == 3) { //Right Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");

                //Send Position to Motor
                pc.printf("Input Degree : \n");
                pc.scanf("%f",&temp);
                if(temp!=9999) {
                    RH = temp;
                    pc.printf("Move Right Hip Motor to %f Degree\n",RH);

                    bcom.setMotorPos(RIGHT_SIDE,RH,temp_RK);
                    temp_RH = RH;


                    /********************Save Data*********************/
                } //else bcom.saveDataToEEPROM(RIGHT_SIDE,MOTOR_UPPER_ANG);

            } while(temp != 9999);

        } else if(option == 4) { //Right Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");

                //Send Position to Motor
                pc.printf("Input Degree : \n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    RK = temp;
                    pc.printf("Move Right Knee Motor to %f Degree\n",RK);

                    bcom.setMotorPos(RIGHT_SIDE,temp_RH,RK);
                    temp_RK = RK;


                    /********************Save Data*********************/
                } //else bcom.saveDataToEEPROM(RIGHT_SIDE,MOTOR_LOWER_ANG);

            } while(temp != 9999);

        } else if(option == 5) { //Left Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kp of Left Hip\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kp of Left Hip to %f",temp);

                    bcom.setUpMotorKp(LEFT_SIDE,temp);
                } else bcom.saveDataToEEPROM(LEFT_SIDE,PID_UPPER_MOTOR);

            } while(temp != 9999);

        } else if(option == 6) { //Left Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Ki of Left Hip\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Ki of Left Hip to %f",temp);

                    bcom.setUpMotorKi(LEFT_SIDE,temp);
                } else bcom.saveDataToEEPROM(LEFT_SIDE,PID_UPPER_MOTOR);

            } while(temp != 9999);

        } else if(option == 7) { //Left Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kd of Left Hip\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kd of Left Hip to %f",temp);

                    bcom.setUpMotorKd(LEFT_SIDE,temp);
                } else bcom.saveDataToEEPROM(LEFT_SIDE,PID_UPPER_MOTOR);

            } while(temp != 9999);

        } else if(option == 8) { //Left Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kp of Left Knee\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kp of Left Knee to %f",temp);

                    bcom.setLowMotorKp(LEFT_SIDE,temp);
                } else bcom.saveDataToEEPROM(LEFT_SIDE,PID_LOWER_MOTOR);

            } while(temp != 9999);

        } else if(option == 9) { //Left Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Ki of Left Knee\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Ki of Left Knee to %f",temp);

                    bcom.setLowMotorKi(LEFT_SIDE,temp);
                } else bcom.saveDataToEEPROM(LEFT_SIDE,PID_LOWER_MOTOR);

            } while(temp != 9999);

        } else if(option == 10) { //Left Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kd of Left Knee\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kd of Left Knee to %f",temp);

                    bcom.setLowMotorKd(LEFT_SIDE,temp);
                } else bcom.saveDataToEEPROM(LEFT_SIDE,PID_LOWER_MOTOR);

            } while(temp != 9999);


        } else if(option == 11) { //Right Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kp of Right Hip\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kp of Right Hip to %f",temp);

                    bcom.setUpMotorKp(RIGHT_SIDE,temp);
                } else bcom.saveDataToEEPROM(RIGHT_SIDE,PID_UPPER_MOTOR);

            } while(temp != 9999);

        } else if(option == 12) { //Right Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Ki of Right Hip\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Ki of Right Hip to %f",temp);

                    bcom.setUpMotorKi(RIGHT_SIDE,temp);
                } else bcom.saveDataToEEPROM(RIGHT_SIDE,PID_UPPER_MOTOR);

            } while(temp != 9999);

        } else if(option == 13) { //Right Hip
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kd of Right Hip\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kd of Right Hip to %f",temp);

                    bcom.setUpMotorKd(RIGHT_SIDE,temp);
                } else bcom.saveDataToEEPROM(RIGHT_SIDE,PID_UPPER_MOTOR);

            } while(temp != 9999);


        } else if(option == 14) { //Right Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kp of Right Knee\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kp of Right Knee to %f",temp);

                    bcom.setLowMotorKp(RIGHT_SIDE,temp);
                } else bcom.saveDataToEEPROM(RIGHT_SIDE,PID_LOWER_MOTOR);

            } while(temp != 9999);

        } else if(option == 15) { //Right Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Ki of Right Knee\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Ki of Right Knee to %f Degree\n",temp);

                    bcom.setLowMotorKi(RIGHT_SIDE,temp);
                } else bcom.saveDataToEEPROM(RIGHT_SIDE,PID_LOWER_MOTOR);

            } while(temp != 9999);

        } else if(option == 16) { //Right Knee
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("\nInput Kd of Right Knee\n");
                pc.scanf("%f",&temp);

                if(temp != 9999) {
                    pc.printf("\nChange Kd of Right Knee to %f",temp);

                    bcom.setLowMotorKd(RIGHT_SIDE,temp);
                } else bcom.saveDataToEEPROM(RIGHT_SIDE,PID_LOWER_MOTOR);

            } while(temp != 9999);


        } else if(option == 17) { //Left Hip Margin
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Margin\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nChange Left Hip Margin to %f\n",temp);
                bcom.setUpMargin(LEFT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(LEFT_SIDE,UP_MARGIN);
        }

        else if(option == 18) { //Left Knee Margin
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Margin\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nChange Left Knee Margin to %f\n",temp);
                bcom.setLowMargin(LEFT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(LEFT_SIDE,LOW_MARGIN);
        }

        else if(option == 19) { //Right Hip Margin
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Margin\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nChange Right Hip Margin to %f\n",temp);
                bcom.setUpMargin(RIGHT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(RIGHT_SIDE,UP_MARGIN);
        }

        else if(option == 20) { //Right Knee Margin
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Margin\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nChange Right Knee Margin to %f\n",temp);
                bcom.setLowMargin(RIGHT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(RIGHT_SIDE,LOW_MARGIN);
        }

        else if(option == 21) { //Lenght of Left Link Hip
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Lenght of Left Link Hip\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nLenght of Left Link Hip = %f\n",temp);
                LLink0 = temp;
                a = true;
                bcom.setUpLinkLength(LEFT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(LEFT_SIDE,UP_LINK_LENGTH);
        }

        else if(option == 22) { //Lenght of Left Link Knee
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Lenght of Left Link Knee\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nLenght of Left Link Knee = %f\n",temp);
                LLink1 = temp;
                b = true;
                bcom.setLowLinkLength(LEFT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(LEFT_SIDE,LOW_LINK_LENGTH);
        }

        else if(option == 23) { //Lenght of Right Link Hip
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Lenght of Right Link Hip\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nLenght of Right Link Hip = %f\n",temp);
                RLink0 = temp;
                c = true;
                bcom.setUpLinkLength(RIGHT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(RIGHT_SIDE,UP_LINK_LENGTH);
        }

        else if(option == 24) { //Lenght of Right Link Knee
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Lenght of Right Link Knee\n");
            pc.scanf("%f",&temp);

            if(temp != 9999) {
                pc.printf("\nLenght of Right Link Knee = %f\n",temp);
                RLink1 = temp;
                d = true;
                bcom.setLowLinkLength(RIGHT_SIDE,temp);
            } //else
            bcom.saveDataToEEPROM(RIGHT_SIDE,LOW_LINK_LENGTH);
        }

        else if(option == 25) { //Offset
            if(a == true && b == true && c == true && d == true) {
                float LHipAngle,LKneeAngle;
                float RHipAngle,RKneeAngle;

                bcom.getMotorPos(LEFT_SIDE,&LHipAngle,&LKneeAngle);
                wait_ms(90);
                bcom.getMotorPos(RIGHT_SIDE,&RHipAngle,&RKneeAngle);
                wait_ms(90);

                Left.set_Link_Hip(LLink0);
                Left.set_Link_Knee(LLink1);
                Left.set_Zeta_Hip(LHipAngle);
                Left.set_Zeta_Knee(LKneeAngle);

                Right.set_Link_Hip(RLink0);
                Right.set_Link_Knee(RLink1);
                Right.set_Zeta_Hip(RHipAngle);
                Right.set_Zeta_Knee(RKneeAngle);

                Left.ForwardKinematicCalculation();
                Right.ForwardKinematicCalculation();

                float offset_Y,offset_Z;
                float y1,y2,z1,z2;
                y1 = Left.get_Position_Y();
                y2 = Right.get_Position_Y();
                z1 = Left.get_Position_Z();
                z2 = Right.get_Position_Z();
                offset_Y = y1-y2;
                offset_Z = z1-z2;

                bcom.setOffset(LEFT_SIDE,offset_Y,offset_Z);

                bcom.saveDataToEEPROM(LEFT_SIDE,OFFSET);

            } else {
                pc.printf("\nYou have to do choice 21-23 first\n\n");
                wait(1);
            }
        }

        else if(option == 26) { //setBodyWidth
            pc.printf("\nType 9999 to Exit to Main Menu\n");
            pc.printf("Input Body Width\n");
            pc.scanf("%f",&temp);
            pc.printf("\nBody Lenght = %f\n",temp);
            bcom.setBodyWidth(LEFT_SIDE,temp);
            bcom.saveDataToEEPROM(LEFT_SIDE,BODY_WIDTH);
        }

        else if(option == 27) { //Set Maximum Hip Angle Range
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("1) Left Side\n");
                pc.printf("2) Right Side\n");
                pc.scanf("%f",&temp);

                if(temp==1) { //Left
                    pc.printf("Input Maximum Hip Angle Range of Left Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMaximum Hip Angle Range of Left Side = %f\n",temp);
                        bcom.setUpAngleRange(LEFT_SIDE,temp,Lmin.Hip);
                        Lmax.Hip = temp;
                    } //else
                    bcom.saveDataToEEPROM(LEFT_SIDE,ANGLE_RANGE_UP);

                } else if(temp==2) { //Right
                    pc.printf("Input Maximum Hip Angle Range of Right Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMaximum Hip Angle Range of Right Side = %f\n",temp);
                        bcom.setUpAngleRange(RIGHT_SIDE,temp,Rmin.Hip);
                        Rmax.Hip = temp;
                    } //else
                    bcom.saveDataToEEPROM(RIGHT_SIDE,ANGLE_RANGE_UP);
                }
            } while(temp!=9999);
        }

        else if(option == 28) { //Set Minumum Hip Angle Range
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("1) Left Side\n");
                pc.printf("2) Right Side\n");
                pc.scanf("%f",&temp);

                if(temp==1) { //Left
                    pc.printf("Input Minumum Hip Angle Range of Left Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMinumum Hip Angle Range of Left Side = %f\n",temp);
                        bcom.setUpAngleRange(LEFT_SIDE,Lmax.Hip,temp);
                        Lmin.Hip = temp;
                    } //else
                    bcom.saveDataToEEPROM(LEFT_SIDE,ANGLE_RANGE_UP);

                } else if(temp==2) { //Right
                    pc.printf("Input Minumum Hip Angle Range of Right Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMinumum Hip Angle Range of Right Side = %f\n",temp);
                        bcom.setUpAngleRange(RIGHT_SIDE,Rmax.Hip,temp);
                        Rmin.Hip = temp;
                    } //else
                    bcom.saveDataToEEPROM(RIGHT_SIDE,ANGLE_RANGE_UP);
                }
            } while(temp!=9999);
        }


        else if(option == 29) { //Set Maximum Knee Angle Range
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("1) Left Side\n");
                pc.printf("2) Right Side\n");
                pc.scanf("%f",&temp);

                if(temp==1) { //Left
                    pc.printf("Input Maximum Knee Angle Range of Left Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMaximum Knee Angle Range of Left Side = %f\n",temp);
                        bcom.setLowAngleRange(LEFT_SIDE,temp,Lmin.Knee);
                        Lmax.Knee = temp;
                    } //else
                    bcom.saveDataToEEPROM(LEFT_SIDE,ANGLE_RANGE_LOW);

                } else if(temp==2) { //Right
                    pc.printf("Input Maximum Knee Angle Range of Right Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMaximum Knee Angle Range of Right Side = %f\n",temp);
                        bcom.setLowAngleRange(RIGHT_SIDE,temp,Rmin.Knee);
                        Rmax.Knee = temp;
                    } //else
                    bcom.saveDataToEEPROM(RIGHT_SIDE,ANGLE_RANGE_LOW);
                }
            } while(temp!=9999);
        }

        else if(option == 30) { //Set Minumum Knee Angle Range
            do {
                pc.printf("\nType 9999 to Exit to Main Menu\n");
                pc.printf("1) Left Side\n");
                pc.printf("2) Right Side\n");
                pc.scanf("%f",&temp);

                if(temp==1) { //Left
                    pc.printf("Input Minumum Knee Angle Range of Left Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMinumum Knee Angle Range of Left Side = %f\n",temp);
                        bcom.setLowAngleRange(LEFT_SIDE,Lmax.Knee,temp);
                        Lmin.Knee = temp;
                    } //else
                    bcom.saveDataToEEPROM(LEFT_SIDE,ANGLE_RANGE_LOW);

                } else if(temp==2) { //Right
                    pc.printf("Input Minumum Knee Angle Range of Right Side\n");
                    pc.scanf("%f",&temp);

                    if(temp != 9999) {
                        pc.printf("\nMinumum Knee Angle Range of Right Side = %f\n",temp);
                        bcom.setLowAngleRange(RIGHT_SIDE,Rmax.Knee,temp);
                        Rmin.Knee = temp;
                    } //else
                    bcom.saveDataToEEPROM(RIGHT_SIDE,ANGLE_RANGE_LOW);
                }
            } while(temp!=9999);
        }






        else if(option == 40) {
            pc.printf("Are You Sure ?\n");
            pc.printf("\n1) Yes\n");
            pc.printf("2) No\n");

            pc.scanf("%d",&option);
            if(option==1) {
                option = 40;
                pc.printf("Please Push Button Restart\n");
            } else pc.printf("Return to Main Menu\n");

        }


        else { // if user has entered invalid choice
            pc.printf("\nInvalid Option entered\n");
        }
    } while(option != 40);

}



int main()
{
    pc.baud(115200);
    sync_communicate.start();

    if(!button) { //Set up mode
        while(!button);
        pc.printf("Switch Mode\n");
        SwMode();
    }

    /*while(1){
        Kinematic test('P',10,15,10,10);
        pc.printf("\n\nLink Hip : %f, Link Knee : %f, Position Y : %f, Position Z : %f\n",test.get_Link_Hip(),test.get_Link_Knee(),test.get_Position_Y(),test.get_Position_Z());
        pc.printf("Zeta Hip : %f, Zeta Knee : %f\n",test.get_Zeta_Hip(),test.get_Zeta_Knee());
        test.set_Link_Hip(25);
        test.set_Link_Knee(30);
        test.set_Position_Y(35);
        test.set_Position_Z(40);
        test.set_Zeta_Hip(45);
        test.set_Zeta_Knee(50);
        pc.printf("\nLink Hip : %f, Link Knee : %f, Position Y : %f, Position Z : %f\n",test.get_Link_Hip(),test.get_Link_Knee(),test.get_Position_Y(),test.get_Position_Z());
        pc.printf("Zeta Hip : %f, Zeta Knee : %f\n",test.get_Zeta_Hip(),test.get_Zeta_Knee());

        while(1);
    }*/

    Init_IMU();

    float temp_time;

    while(1) {
        temp_time = t.read();
        // If intPin goes high, all data registers have new data
        if(mpu9250.readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01) {  // On interrupt, check if data ready interrupt

            mpu9250.readAccelData(accelCount);  // Read the x/y/z adc values
            // Now we'll calculate the accleration value into actual g's
            ax = (float)accelCount[0]*aRes - accelBias[0];  // get actual g value, this depends on scale being set
            ay = (float)accelCount[1]*aRes - accelBias[1];
            az = (float)accelCount[2]*aRes - accelBias[2];

            mpu9250.readGyroData(gyroCount);  // Read the x/y/z adc values
            // Calculate the gyro value into actual degrees per second
            gx = (float)gyroCount[0]*gRes - gyroBias[0];  // get actual gyro value, this depends on scale being set
            gy = (float)gyroCount[1]*gRes - gyroBias[1];
            gz = (float)gyroCount[2]*gRes - gyroBias[2];

            mpu9250.readMagData(magCount);  // Read the x/y/z adc values
            // Calculate the magnetometer values in milliGauss
            // Include factory calibration per data sheet and user environmental corrections
            /*   if(magCount[0]<xmin)
                   xmin = magCount[0];
               if(magCount[0]>xmax)
                   xmax = magCount[0];

               if(magCount[1]<ymin)
                   ymin = magCount[1];
               if(magCount[1]>ymax)
                   ymax = magCount[1];

               if(magCount[2]<zmin)
                   zmin = magCount[2];
               if(mz>zmax)
                   zmax = mz;
               wait_ms(1);
            */
            // pc.printf("FINISH scan\r\n\r\n");

//            mx = (float)magCount[0]*mRes*magCalibration[0] + magbias[0];  // get actual magnetometer value, this depends on scale being set
//            my = (float)magCount[1]*mRes*magCalibration[1] + magbias[1];
//            mz = (float)magCount[2]*mRes*magCalibration[2] + magbias[2];

            mx = ((float)magCount[0]-xmin)*magCalibration[0] + magbias[0];  // get actual magnetometer value, this depends on scale being set
            my = ((float)magCount[1]-ymin)*magCalibration[1] + magbias[1];
            mz = ((float)magCount[2]-zmin)*magCalibration[2] + magbias[2];

            // mx = (float)magCount[0]*1.499389499f - magbias[0];  // get actual magnetometer value, this depends on scale being set
            // my = (float)magCount[1]*1.499389499f - magbias[1];
            // mz = (float)magCount[2]*1.499389499f - magbias[2];




        }

        Now = t.read_us();
        deltat = (float)((Now - lastUpdate)/1000000.0f) ; // set integration time by time elapsed since last filter update
        lastUpdate = Now;

        sum += deltat;
        sumCount++;

//    if(lastUpdate - firstUpdate > 10000000.0f) {
//     beta = 0.04;  // decrease filter gain after stabilized
//     zeta = 0.015; // increasey bias drift gain after stabilized
//   }

        // Pass gyro rate as rad/s
        //mpu9250.MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f,  my,  mx, mz);
        mpu9250.MahonyQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f, my, mx, mz);

        // Serial print and/or display at 0.5 s rate independent of data rates
        delt_t = t.read_ms() - count;
        if(temp_time > 8) {
            if (delt_t > 500) { // update LCD once per half-second independent of read rate

                /*pc.printf("ax = %f", 1000*ax);
                pc.printf(" ay = %f", 1000*ay);
                pc.printf(" az = %f  mg\n\r", 1000*az);

                pc.printf("gx = %f", gx);
                pc.printf(" gy = %f", gy);
                pc.printf(" gz = %f  deg/s\n\r", gz);

                pc.printf("mx = %f", mx);
                pc.printf(" my = %f", my);
                pc.printf(" mz = %f  mG\n\r", mz);*/

                uint8_t whoami = mpu9250.readByte(AK8963_ADDRESS, AK8963_ST2);  // Read WHO_AM_I register for MPU-9250
                // pc.printf("I AM 0x%x\n\r", whoami); pc.printf("I SHOULD BE 0x10\n\r");
                if(whoami == 0x14) {
                    pc.printf("I AM 0x%x\n\r", whoami);
                    while(1);
                }


                tempCount = mpu9250.readTempData();  // Read the adc values
                temperature = ((float) tempCount) / 333.87f + 21.0f; // Temperature in degrees Centigrade
                //pc.printf(" temperature = %f  C\n\r", temperature);

                // pc.printf("q0 = %f\n\r", q[0]);
                // pc.printf("q1 = %f\n\r", q[1]);
                // pc.printf("q2 = %f\n\r", q[2]);
                // pc.printf("q3 = %f\n\r", q[3]);

                // Define output variables from updated quaternion---these are Tait-Bryan angles, commonly used in aircraft orientation.
                // In this coordinate system, the positive z-axis is down toward Earth.
                // Yaw is the angle between Sensor x-axis and Earth magnetic North (or true North if corrected for local declination, looking down on the sensor positive yaw is counterclockwise.
                // Pitch is angle between sensor x-axis and Earth ground plane, toward the Earth is positive, up toward the sky is negative.
                // Roll is angle between sensor y-axis and Earth ground plane, y-axis up is positive roll.
                // These arise from the definition of the homogeneous rotation matrix constructed from quaternions.
                // Tait-Bryan angles as well as Euler angles are non-commutative; that is, the get the correct orientation the rotations must be
                // applied in the correct order which for this configuration is yaw, pitch, and then roll.
                // For more see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles which has additional links.
                yaw   = atan2(2.0f * (q[1] * q[2] + q[0] * q[3]), q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]);
                pitch = -asin(2.0f * (q[1] * q[3] - q[0] * q[2]));
                roll  = atan2(2.0f * (q[0] * q[1] + q[2] * q[3]), q[0] * q[0] - q[1] * q[1] - q[2] * q[2] + q[3] * q[3]);

                float Xh = mx*cos(pitch)+my*sin(roll)*sin(pitch)-mz*cos(roll)*sin(pitch);
                float Yh = my*cos(roll)+mz*sin(roll);

                float yawmag = atan2(Yh,Xh)+PI;
                //pc.printf("Xh= %f Yh= %f ",Xh,Yh);
                //pc.printf("Yaw[mag]= %f\n\r",yawmag*180.0f/PI);



                pitch *= 180.0f / PI;
                yaw   *= 180.0f / PI;
                yaw   += 180.0f; // Declination at Danville, California is 13 degrees 48 minutes and 47 seconds on 2014-04-04
                roll  *= 180.0f / PI;

                pc.printf("Yaw, Pitch, Roll: %f %f %f\n\r", yaw, pitch, roll);
                //pc.printf("average rate = %f\n\r", (float) sumCount/sum);


                WheelChair();


                myled= !myled;
                count = t.read_ms();

                if(count > 1<<21) {
                    t.start(); // start the timer over again if ~30 minutes has passed
                    count = 0;
                    deltat= 0;
                    lastUpdate = t.read_us();
                }
                sum = 0;
                sumCount = 0;
            }
        }
    }
}

void Init_IMU()
{

    //Set up I2C
    i2c.frequency(400000);  // use fast (400 kHz) I2C

    pc.printf("CPU SystemCoreClock is %d Hz\r\n", SystemCoreClock);

    t.start();

    //mpu9250.resetMPU9250();
    // Read the WHO_AM_I register, this is a good test of communication
    uint8_t whoami = mpu9250.readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250);  // Read WHO_AM_I register for MPU-9250
    pc.printf("I AM 0x%x\n\r", whoami);
    pc.printf("I SHOULD BE 0x71\n\r");

    if (whoami == 0x71) { // WHO_AM_I should always be 0x68
        pc.printf("MPU9250 WHO_AM_I is 0x%x\n\r", whoami);
        pc.printf("MPU9250 is online...\n\r");
        sprintf(buffer, "0x%x", whoami);
        wait(1);

        mpu9250.resetMPU9250(); // Reset registers to default in preparation for device calibration
        mpu9250.MPU9250SelfTest(SelfTest); // Start by performing self test and reporting values
        pc.printf("x-axis self test: acceleration trim within : %f % of factory value\n\r", SelfTest[0]);
        pc.printf("y-axis self test: acceleration trim within : %f % of factory value\n\r", SelfTest[1]);
        pc.printf("z-axis self test: acceleration trim within : %f % of factory value\n\r", SelfTest[2]);
        pc.printf("x-axis self test: gyration trim within : %f % of factory value\n\r", SelfTest[3]);
        pc.printf("y-axis self test: gyration trim within : %f % of factory value\n\r", SelfTest[4]);
        pc.printf("z-axis self test: gyration trim within : %f % of factory value\n\r", SelfTest[5]);
        mpu9250.calibrateMPU9250(gyroBias, accelBias); // Calibrate gyro and accelerometers, load biases in bias registers
        pc.printf("x gyro bias = %f\n\r", gyroBias[0]);
        pc.printf("y gyro bias = %f\n\r", gyroBias[1]);
        pc.printf("z gyro bias = %f\n\r", gyroBias[2]);
        pc.printf("x accel bias = %f\n\r", accelBias[0]);
        pc.printf("y accel bias = %f\n\r", accelBias[1]);
        pc.printf("z accel bias = %f\n\r", accelBias[2]);
        wait(2);
        mpu9250.initMPU9250();
        pc.printf("MPU9250 initialized for active data mode....\n\r"); // Initialize device for active mode read of acclerometer, gyroscope, and temperature
        mpu9250.initAK8963(magCalibration);
        pc.printf("AK8963 initialized for active data mode....\n\r"); // Initialize device for active mode read of magnetometer

        whoami = mpu9250.readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);  // Read WHO_AM_I register for MPU-9250
        pc.printf("I AM 0x%x\n\r", whoami);
        pc.printf("I SHOULD BE 0x48\n\r");
        if(whoami != 0x48) {
            while(1);
        }
        pc.printf("Accelerometer full-scale range = %f  g\n\r", 2.0f*(float)(1<<Ascale));
        pc.printf("Gyroscope full-scale range = %f  deg/s\n\r", 250.0f*(float)(1<<Gscale));
        if(Mscale == 0) pc.printf("Magnetometer resolution = 14  bits\n\r");
        if(Mscale == 1) pc.printf("Magnetometer resolution = 16  bits\n\r");
        if(Mmode == 2) pc.printf("Magnetometer ODR = 8 Hz\n\r");
        if(Mmode == 6) pc.printf("Magnetometer ODR = 100 Hz\n\r");
        wait(1);
    } else {
        pc.printf("Could not connect to MPU9250: \n\r");
        pc.printf("%#x \n",  whoami);

        sprintf(buffer, "WHO_AM_I 0x%x", whoami);

        while(1) ; // Loop forever if communication doesn't happen
    }

    mpu9250.getAres(); // Get accelerometer sensitivity
    mpu9250.getGres(); // Get gyro sensitivity
    mpu9250.getMres(); // Get magnetometer sensitivity
    pc.printf("Accelerometer sensitivity is %f LSB/g \n\r", 1.0f/aRes);
    pc.printf("Gyroscope sensitivity is %f LSB/deg/s \n\r", 1.0f/gRes);
    pc.printf("Magnetometer sensitivity is %f LSB/G \n\r", 1.0f/mRes);

    /*pc.printf("START scan mag\n\r\n\r\n\r");
    //wait(1);
    for(int i=0; i<4000; i++) {
        mpu9250.readMagData(magCount);

        if(magCount[0]<xmin)
            xmin = magCount[0];
        if(magCount[0]>xmax)
            xmax = magCount[0];

        if(magCount[1]<ymin)
            ymin = magCount[1];
        if(magCount[1]>ymax)
            ymax = magCount[1];

        if(magCount[2]<zmin)
            zmin = magCount[2];
        if(magCount[2]>zmax)
            zmax = magCount[2];


        wait_ms(10);
    }
    pc.printf("FINISH scan\r\n\r\n");
    pc.printf("Mx Max= %f Min= %f\n\r",xmax,xmin);
    pc.printf("My Max= %f Min= %f\n\r",ymax,ymin);
    pc.printf("Mz Max= %f Min= %f\n\r",zmax,zmin);*/

    /*xmax = 188.000000;
    xmin = -316.000000;
    ymax = 485.000000;
    ymin = -26.000000;
    zmax = 165.000000;
    xmin = -230.000000;

    //Ice room
    xmax = 101.000000;
    xmin = -296.000000;
    ymax = 320.000000;
    ymin = -85.000000;
    zmax = 208.000000;
    xmin = -202.000000;

    xmax = 115.000000;
    xmin = -309.000000;
    ymax = 350.000000;
    ymin = -119.000000;
    zmax = 235.000000;
    zmin = -224.000000;*/

    xmax = 120.000000;
    xmin = -306.000000;
    ymax = 340.000000;
    ymin = -90.000000;
    zmax = 219.000000;
    zmin = -195.000000;



    magbias[0] = -1.0;
    magbias[1] = -1.0;
    magbias[2] = -1.0;

    magCalibration[0] = 2.0f / (xmax -xmin);
    magCalibration[1] = 2.0f / (ymax -ymin);
    magCalibration[2] = 2.0f / (zmax -zmin);

    //magbias[0] = (xmin-xmax)/2.0f;  // User environmental x-axis correction in milliGauss, should be automatically calculated
    //magbias[1] = (ymin-ymax)/2.0f;  // User environmental x-axis correction in milliGauss
    //magbias[2] = (zmin-zmax)/2.0f;  // User environmental x-axis correction in milliGauss
    pc.printf("mag[0] %f",magbias[0]);
    pc.printf("mag[1] %f",magbias[1]);
    pc.printf("mag[2] %f\n\r",magbias[2]);
    //     resalt = atan(magY+((yMin-yMax)/2),magX+(xMin-xMax)/2))*180/PI;

}


void Init_Stabilizer()
{




}

void WheelChair()
{
    //Start Here
    //Stabilize.set_Body_Lenght(5);
    Stabilize.set_current_zeta(roll);
    //Stabilize.set_zeta_set(0);
    //Stabilize.ZetaErrorCalculation();
    Stabilize.PID();

    Stabilize.set_New_Height(Left.get_Position_Z());

    //pc.printf("Height : %f, delta : %f, New Height : %f\n",L.get_Position_Z(),Stabilize.get_delta_h(),Stabilize.get_New_Height());
    Left.print();
    Left.set_Position_Z(Stabilize.get_New_Height());
    Left.InverseKinematicCalculation();
    Left.print();

    Right.set_Position_Y(Left.get_Position_Y()+Stabilize.get_Offset_Y());
    Right.set_Position_Z(Left.get_Position_Z()+Stabilize.get_Offset_Z());
    //R.set_offset_YZ(3,3);
    //R.SumPositionWithOffset();
    Right.InverseKinematicCalculation();
    Right.print();
    pc.printf("\n");

    //Send Position of L&R Angle to Motion Board



    //End Here
}