Penguin Zhou
Penguin Zhou

Reputation: 131

How to set MPU6500 to work and read the accelerometer?

I am working for a small project that I am interested in and I have been working on getting MPU6500's accelerometer's data using Arduino. However, my code just does not work. Every register that I read from wire is -1. Anyone who knows how to make it work right?

Here is my code. I am using Arduino Uno btw.

#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
//Some of those boards have a pull-down resistor at AD0 (address = 0x68), others have a pull-up resistor (address = 0x69).
int16_t AcX,AcY,AcZ;

float time;

void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  //or one, I am not so sure 
  delay(100);
  Wire.write(0x68); 
  Wire.write(0); 
  delay(100);
  Wire.endTransmission(true);
  Serial.begin(115200);
  time = micros();
}

void loop() {
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,6,true);  // request a total of 6 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)

  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.println(AcZ);

  //delay(333);
  float temp = time - micros();
  Serial.println(temp);
  time = micros();

}

Upvotes: 1

Views: 7879

Answers (1)

Ryuuk
Ryuuk

Reputation: 99

#include<Wire.h>

void setup()
{
  Wire.begin();
  Wire.setClock(400000UL); // Set I2C frequency to 400kHz
  Wire.beginTransmission(mpu_addr);
  Wire.write(0x6B);
  Wire.write(0); // wake up the mpu6050
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop() {            

}

double Gyro_X()
{
  Wire.beginTransmission(mpu_addr);
  Wire.write(0x43);
  Wire.endTransmission(false);
  Wire.requestFrom(mpu_addr,2);
  double GyX=Wire.read()<<8|Wire.read();
  Wire.endTransmission(true);
  return GyX;
}

double Acc_Y()
{
  Wire.beginTransmission(mpu_addr);
  Wire.write(0x3D);
  Wire.endTransmission(false);
  Wire.requestFrom(mpu_addr,2);
  double AccY=Wire.read()<<8|Wire.read();
  Wire.endTransmission(true);
  return AccY;  
}

double Acc_Z()
{
  Wire.beginTransmission(mpu_addr);
  Wire.write(0x3F);
  Wire.endTransmission(false);
  Wire.requestFrom(mpu_addr,2);
  double AccZ=Wire.read()<<8|Wire.read();
  Wire.endTransmission(true);
  return AccZ;  
}

Upvotes: 1

Related Questions