stm32f103c8t6软件读取mpu6050角度的程序
时间: 2023-09-02 11:12:05 浏览: 74
以下是一个简单的程序,用于读取 MPU6050 的角度,并在串口输出:
```
#include "stm32f10x.h"
#include "stdio.h"
#include "math.h"
#define MPU_ADDRESS 0xD0
#define MPU_SMPLRT_DIV 0x19
#define MPU_CONFIG 0x1A
#define MPU_GYRO_CONFIG 0x1B
#define MPU_ACCEL_CONFIG 0x1C
#define MPU_ACCEL_XOUT_H 0x3B
#define MPU_ACCEL_YOUT_H 0x3D
#define MPU_ACCEL_ZOUT_H 0x3F
#define MPU_TEMP_OUT_H 0x41
#define MPU_GYRO_XOUT_H 0x43
#define MPU_GYRO_YOUT_H 0x45
#define MPU_GYRO_ZOUT_H 0x47
#define PI 3.14159265359
float Acc_X, Acc_Y, Acc_Z;
float Gyro_X, Gyro_Y, Gyro_Z;
float roll, pitch;
void delay(int ms)
{
for(int i = 0; i < ms * 4000; i++) {}
}
void MPU6050_Init()
{
// Set sample rate divider to 0
I2C1_WriteReg(MPU_ADDRESS, MPU_SMPLRT_DIV, 0x00);
// Set gyro full scale range to +- 250 deg/s
I2C1_WriteReg(MPU_ADDRESS, MPU_GYRO_CONFIG, 0x00);
// Set accelerometer full scale range to +- 2g
I2C1_WriteReg(MPU_ADDRESS, MPU_ACCEL_CONFIG, 0x00);
// Disable FSYNC and set DLPF bandwidth to 42 Hz
I2C1_WriteReg(MPU_ADDRESS, MPU_CONFIG, 0x06);
}
void MPU6050_Read_Accel()
{
uint8_t buf[6];
I2C1_ReadRegs(MPU_ADDRESS, MPU_ACCEL_XOUT_H, buf, 6);
Acc_X = (float)((int16_t)(buf[0] << 8 | buf[1])) / 16384.0;
Acc_Y = (float)((int16_t)(buf[2] << 8 | buf[3])) / 16384.0;
Acc_Z = (float)((int16_t)(buf[4] << 8 | buf[5])) / 16384.0;
}
void MPU6050_Read_Gyro()
{
uint8_t buf[6];
I2C1_ReadRegs(MPU_ADDRESS, MPU_GYRO_XOUT_H, buf, 6);
Gyro_X = (float)((int16_t)(buf[0] << 8 | buf[1])) / 131.0;
Gyro_Y = (float)((int16_t)(buf[2] << 8 | buf[3])) / 131.0;
Gyro_Z = (float)((int16_t)(buf[4] << 8 | buf[5])) / 131.0;
}
void MPU6050_Calc_Angles()
{
roll = atan2(Acc_Y, Acc_Z) * 180.0 / PI;
pitch = atan2(-Acc_X, sqrt(Acc_Y * Acc_Y + Acc_Z * Acc_Z)) * 180.0 / PI;
}
int main()
{
// Initialize I2C
I2C1_Init();
// Initialize MPU6050
MPU6050_Init();
while(1)
{
MPU6050_Read_Accel();
MPU6050_Read_Gyro();
MPU6050_Calc_Angles();
printf("Roll: %f, Pitch: %f\r\n", roll, pitch);
delay(100);
}
}
```
注意,以上程序只是一个简单的示例,可能需要根据实际情况进行修改。例如,根据 MPU6050 的具体型号和连接方式,可能需要修改一些寄存器地址的定义,以及 I2C 的初始化参数等。
阅读全文