Gyroscope and Accelorometer

In this project, you'll learn how to connect and control the GY-521 gyro and accelerometer module which uses the MPU-6050 sensor chip to detect the spin, tilt, and acceleration of an object.

Parts needed: GY-521 gyro and accelerometer

You may want to first read about the I2C protocol before you continue.

1 Making the connections
  • Connect the SCL pin on the compass to pin A5 on the Arduino.
  • Connect the SDA pin on the compass to pin A4 on the Arduino.
  • Connect Vcc to 5V.
  • Connect GND to GND.
2 Create a new program and type in this code.


To understand the register usage and values to read/write to the registers, you'll need to look at the register usage for the MPU-6050 sensor chip.
// Copyright 2017 Enoch Hwang
#include <Wire.h>

#define I2C_address 0x68 //I2C Address for the MPU-6050

void setup(){  
  Serial.begin(9600);
  Wire.begin();
  
  Wire.beginTransmission(I2C_address);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission();
}

void loop(){
  int AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

  //Tell the chip what register to start reading from
  Wire.beginTransmission(I2C_address);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);  
 
 //Read the data. 14 bytes total
  Wire.requestFrom(I2C_address, 14, true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)    
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.println(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}
3 Run the program and open the Serial Monitor to see the gyro and accelerometer values.