Sharifdeen Ashshak
Published

How to make MPU-6050 Accelerometer and Gyroscope Robot

In this project, I'm going to show you how to make a MPU6050 based small hand gesture robot. It only can rotate its head from your hand gest

BeginnerFull instructions provided1 hour2,659
How to make MPU-6050 Accelerometer and Gyroscope Robot

Things used in this project

Story

Read more

Schematics

circuit

Code

code

C/C++
#include <Servo.h>                 //Include Servo Motor library for using Servo 
#include <LiquidCrystal.h>         //Include LCD library for using LCD 
#include <Wire.h>                  //Include WIre library for using I2C 
//#include <MPU6050.h>

LiquidCrystal lcd(2,3,4,5,6,7);   //Define LCD display pins RS,E,D4,D5,D6,D7

const int MPU_addr=0x68;         //I2C MPU6050 Address

Servo myservo;                  //myservo object for class servo 

int16_t axis_X,axis_Y,axis_Z;    

int minVal=265;
int maxVal=402;

double x;
double y;
double z;

int pos = 0;  

void setup()
{
  Wire.begin();                        //Begins I2C communication
  Wire.beginTransmission(MPU_addr);    //Begins Transmission with MPU6050
  Wire.write(0x6B);                    //Puts MPU6050 in Sleep Mode
  Wire.write(0);                       //Puts MPU6050 in power mode 
  Wire.endTransmission(true);          //Ends Trasmission
  
  myservo.attach(9);               //Servo PWM pin as 9 in UNO
  lcd.begin(16,2);                 //Sets LCD in 16X2 Mode
  lcd.print("BLACK KEYHOLE");   
  delay(1000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Arduino");
  lcd.setCursor(0,1);
  lcd.print("MPU6050");
  delay(2000);
  lcd.clear();
  Serial.begin(115200);
}

void loop()
{
  Wire.beginTransmission(MPU_addr); //Begins I2C transmission 
  Wire.write(0x3B);                 //Start with register 0x3B (ACCEL_XOUT_H)             
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true); //Request 14 Registers from MPU6050
  
  axis_X=Wire.read()<<8|Wire.read(); //Obtain 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) 
  axis_Y=Wire.read()<<8|Wire.read(); //0x3B (ACCEL_YOUT_H) & 0x3C (ACCEL_YOUT_L)
  axis_Z=Wire.read()<<8|Wire.read(); //0x3B (ACCEL_ZOUT_H) & 0x3C (ACCEL_ZOUT_L)
    
    int xAng = map(axis_X,minVal,maxVal,-90,90); 
    int yAng = map(axis_Y,minVal,maxVal,-90,90);
    int zAng = map(axis_Z,minVal,maxVal,-90,90);

   x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);     //Formula to calculate x values in degree
     int pos = map(x,0,180,0,180); // As X value is from 0 to 360 deg
     myservo.write(pos);           // Write angle obtained 0 to 180 to servo
     lcd.setCursor(0,0);
     lcd.print("Angle");
     lcd.setCursor(0,1);
     lcd.print(x); 
     Serial.println("Angle:");
     Serial.print(x);
     Serial.print('\n');               
     delay(500);
     lcd.clear();
}

Credits

Sharifdeen Ashshak
34 projects • 44 followers
Ai, IoT, embedded enthusiast

Comments