Accelerometer working



Joined: Mar 28, 2018

Replies: 0
Accelerometer working
March 28, 2018 - 9:23pm

MPU6050 mpu;

int 16_t ax, ay, az, gx, gy, gz;

int vx, vy;

int button1 = 6;

int button2 = 7;

int buttonState1 = 0; 

int buttonState2 = 0; 

void setup()



     pinMode(button1, INPUT);

     pinMode(button2, INPUT);


     if (!mpu.testConnection())
          while (1);

void loop() 

         mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

         vx = (gx+15)/150; 
        vy = -(gz-100)/150;

         Serial.print("gx = ");

         Serial.print(" | gz = ");

       Serial.print("        | X = ");


         Serial.print(" | Y = ");

         Mouse.move(vx, vy);

         buttonState1 = digitalRead(button1);
         buttonState2 = digitalRead(button2);

           if (buttonState1 == HIGH)


            else if(buttonState2 == HIGH)







Hi sir, I am A.Durga Saranya. Sir the above code is for gesture based mouse control. It is working correctly but the movement of the mouse is not according to the movement of our hand. But the left click and right click are working correctly. When we move our hand in one direction it will move in some other direction. Sir, I contacted  you with the  hope that you will help me. Please tell me whether any changes should be made to the code. Please sir, I request you my project date is getting nearer and I have only three days. Please reply sir.

Aswinth Raj's picture


Joined: Aug 16, 2016

Replies: 953
Hope you got the problem
April 6, 2018 - 9:49am

Hope you got the problem resolved. 

The problem should have mostly been an uncalibrated accelerometer. Make sure your code calibrates the MPU6050 (makes all values zero) before startign to move the cursor. Also what do you been by "some other direction" . If it is moving exactly in the opposite direction  then change the line        Mouse.move(vx, vy); to  

       Mouse.move(vy, vx);