EC_Nano130_Control_MPU9250_Sensor_V1.00.zip
(8.22 MB)
本范例介绍如何使用 NANO130 与运动传感器 MPU9250 通讯以获取设备的运动轨迹和方向。
首先,Nano130 通过 I2C 接口对 MPU9250 进行初始化,设定模式为 Measurement Mode,取样频率为 125Hz,频宽为 5Hz,加速度测量范围±2g,角速度测量范围±2000 dps。
然后,通过 I2C 总线发出指令获取 MPU9250 测量到的九个数值,我们可以拿这些数值来做一些有趣的应用,比如,用加速度及角速度值记录移动轨迹,用磁力数值判断移动方向。
首先初始化 MPU9250:
// Init MPU9250
void Init_MPU9250(void)
{
I2C0_Write(GYRO_ADDRESS, PWR_MGMT_1, 0x00);
I2C0_Write(GYRO_ADDRESS, SMPLRT_DIV, 0x07);
I2C0_Write(GYRO_ADDRESS, CONFIG, 0x06);
I2C0_Write(GYRO_ADDRESS, GYRO_CONFIG, 0x18);
I2C0_Write(GYRO_ADDRESS, ACCEL_CONFIG, 0x01);
}
MCU 通过 I2C 获取 MPU9250 传感器测量到的加速度值,角速度值和磁力计值:
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] Obtaining Accelerometer values (RAW Data)
* @param none
* [url=home.php?mod=space&uid=266161]@return[/url] none
*
* [url=home.php?mod=space&uid=1543424]@Details[/url] Obtaining Accelerometer values
*/
void READ_MPU9250_ACCEL(void)
{
BUF[0] = I2C0_Read(ACCEL_ADDRESS, ACCEL_XOUT_L);
BUF[1] = I2C0_Read(ACCEL_ADDRESS, ACCEL_XOUT_H);
T_X = (BUF[1] << 8) | BUF[0];
T_X /= 164;
BUF[2] = I2C0_Read(ACCEL_ADDRESS, ACCEL_YOUT_L);
BUF[3] = I2C0_Read(ACCEL_ADDRESS, ACCEL_YOUT_H);
T_Y = (BUF[3] << 8) | BUF[2];
T_Y /= 164;
BUF[4] = I2C0_Read(ACCEL_ADDRESS, ACCEL_ZOUT_L);
BUF[5] = I2C0_Read(ACCEL_ADDRESS, ACCEL_ZOUT_H);
T_Z = (BUF[5] << 8) | BUF[4];
T_Z /= 164;
}
/**
* @brief Obtaining gyroscope values (RAW Data)
* @param none
* @return none
*
* @details Obtaining gyroscope values
*/
void READ_MPU9250_GYRO(void)
{
BUF[0] = I2C0_Read(GYRO_ADDRESS, GYRO_XOUT_L);
BUF[1] = I2C0_Read(GYRO_ADDRESS, GYRO_XOUT_H);
T_X = (BUF[1] << 8) | BUF[0];
T_X /= 16.4;
BUF[2] = I2C0_Read(GYRO_ADDRESS, GYRO_YOUT_L);
BUF[3] = I2C0_Read(GYRO_ADDRESS, GYRO_YOUT_H);
T_Y = (BUF[3] << 8) | BUF[2];
T_Y /= 16.4;
BUF[4] = I2C0_Read(GYRO_ADDRESS, GYRO_ZOUT_L);
BUF[5] = I2C0_Read(GYRO_ADDRESS, GYRO_ZOUT_H);
T_Z = (BUF[5] << 8) | BUF[4];
T_Z /= 16.4;
}
/**
* @brief Obtaining Magnetomet values (RAW Data)
* @param none
* @return none
*
* @details Obtaining Magnetomet values
*/
void READ_MPU9250_MAG(void)
{
I2C0_Write(GYRO_ADDRESS, 0x37, 0x02); //turn on Bypass Mode
CLK_SysTickDelay(10000);
I2C0_Write(MAG_ADDRESS, 0x0A, 0x01);
CLK_SysTickDelay(10000);
BUF[0] = I2C0_Read(MAG_ADDRESS, MAG_XOUT_L);
BUF[1] = I2C0_Read(MAG_ADDRESS, MAG_XOUT_H);
T_X = (BUF[1] << 8) | BUF[0];
BUF[2] = I2C0_Read(MAG_ADDRESS, MAG_YOUT_L);
BUF[3] = I2C0_Read(MAG_ADDRESS, MAG_YOUT_H);
T_Y = (BUF[3] << 8) | BUF[2];
BUF[4] = I2C0_Read(MAG_ADDRESS, MAG_ZOUT_L);
BUF[5] = I2C0_Read(MAG_ADDRESS, MAG_ZOUT_H);
T_Z = (BUF[5] << 8) | BUF[4];
}
通过串口 1 将获取的数值打印出来:
READ_MPU9250_ACCEL(); // Gravity acceleration 0.01g
printf("ACCEL: X: %4d Y: %4d Z: %4d /0.01 g\n", T_X, T_Y, T_Z);
READ_MPU9250_GYRO(); //angular velocity 1dps
printf("GYRO : X: %4d Y: %4d Z: %4d /1 dps\n", T_X, T_Y, T_Z);
READ_MPU9250_MAG(); //Magnetometer
printf("MAG : X: %4d Y: %4d Z: %4d /0.6 uT\n\n\n", T_X, T_Y, T_Z);
|