我正在尝试从 MPU9250 读取数据。加速度计和陀螺仪读数正常。但我无法从磁力计中成功读取任何内容。查看数据表,关于设置的一切看起来都井井有条。
ST1 磁力计寄存器也未被读取。每次为磁力计调用
I2Cread
函数时,调试打印 Serial.print("Wire available: "); Serial.println(Wire.available());
打印 0(据我所知,这意味着没有任何可用字节可读)。非常感谢任何建议或帮助。提前致谢。
这是我的代码:
#include <Wire.h>
#include <Arduino.h>
#define MPU9250_ADDRESS 0x68
#define MAG_ADDRESS 0x0C
#define GYRO_FULL_SCALE_250_DPS 0x00
#define GYRO_FULL_SCALE_500_DPS 0x08
#define GYRO_FULL_SCALE_1000_DPS 0x10
#define GYRO_FULL_SCALE_2000_DPS 0x18
#define ACC_FULL_SCALE_2_G 0x00
#define ACC_FULL_SCALE_4_G 0x08
#define ACC_FULL_SCALE_8_G 0x10
#define ACC_FULL_SCALE_16_G 0x18
void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t* Data)
{
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.endTransmission();
Wire.requestFrom(Address, Nbytes);
uint8_t index = 0;
Serial.print("Wire available: ");
Serial.println(Wire.available());
while (Wire.available())
{
Serial.println("Data array data:");
Data[index++] = Wire.read();
Serial.print(index-1);
Serial.print("\t");
Serial.println(Data[index-1]);
}
}
void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)
{
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.write(Data);
Wire.endTransmission();
}
void setup()
{
Wire.begin();
Serial.begin(115200);
I2CwriteByte(MPU9250_ADDRESS, 28, ACC_FULL_SCALE_16_G);
I2CwriteByte(MPU9250_ADDRESS, 27, GYRO_FULL_SCALE_2000_DPS);
// enable mag sensor bypass
I2CwriteByte(MPU9250_ADDRESS, 0x37, 0x22);
I2CwriteByte(MAG_ADDRESS, 0x0A, 0x01);
delay(20);
//I2CwriteByte(MAG_ADDRESS, 0x0A, 0x00);
}
void loop()
{
uint8_t Buf[14];
I2Cread(MPU9250_ADDRESS, 0x3B, 14, Buf);
int16_t ax = -(Buf[0] << 8 | Buf[1]);
int16_t ay = -(Buf[2] << 8 | Buf[3]);
int16_t az = Buf[4] << 8 | Buf[5];
int16_t gx = -(Buf[8] << 8 | Buf[9]);
int16_t gy = -(Buf[10] << 8 | Buf[11]);
int16_t gz = Buf[12] << 8 | Buf[13];
uint8_t ST1;
//I2CwriteByte(MAG_ADDRESS, 0x0A, 0x01);
delay(20);
do
{
I2Cread(MAG_ADDRESS, 0x02, 1, &ST1); // not read, 0 bytes available in read
Serial.print("ST1: ");
Serial.println(ST1);
}
while (!(ST1 & 0x01));
uint8_t Mag[7];
I2Cread(MAG_ADDRESS, 0x03, 7, Mag);
//I2CwriteByte(MAG_ADDRESS, 0x0A, 0x00);
Serial.println("Mag array data:");
for (size_t i = 0; i < 7; i++)
{
Serial.print(i);
Serial.print("\t");
Serial.println(Mag[i]);
}
int16_t mx = -(Mag[3] << 8 | Mag[2]);
int16_t my = -(Mag[1] << 8 | Mag[0]);
int16_t mz = -(Mag[5] << 8 | Mag[4]);
Serial.print(ax, DEC);
Serial.print("\t");
Serial.print(ay, DEC);
Serial.print("\t");
Serial.print(az, DEC);
Serial.print("\t");
Serial.print(gx, DEC);
Serial.print("\t");
Serial.print(gy, DEC);
Serial.print("\t");
Serial.print(gz, DEC);
Serial.print("\t");
Serial.print(mx + 200, DEC);
Serial.print("\t");
Serial.print(my - 70, DEC);
Serial.print("\t");
Serial.print(mz - 700, DEC);
Serial.print("\t");
Serial.println("");
delay(500);
}