- #include <Wire.h>
- #include <Adafruit_MPU6050.h>
- #include <Adafruit_Sensor.h>
- Adafruit_MPU6050 mpu;
- void setup() {
- Serial.begin(9600);
- while (!Serial) delay(10);
- if (!mpu.begin()) {
- Serial.println("MPU6050初始化失败!");
- while (1);
- }
-
- // 传感器参数配置
- mpu.setAccelerometerRange(MPU6050_RANGE_8_G); // 加速度计量程 ±8G
- mpu.setGyroRange(MPU6050_RANGE_500_DEG); // 陀螺仪量程 ±500°/s
- mpu.setFilterBandwidth(MPU6050_BAND_21_HZ); // 滤波器带宽 21Hz
- }
- void loop() {
- sensors_event_t a, g, temp;
- mpu.getEvent(&a, &g, &temp); // 获取传感器事件
- // 通过加速度计计算角度(静态精度高)
- float roll = atan2(a.acceleration.y, a.acceleration.z) * 180/M_PI;
- float pitch = atan2(-a.acceleration.x, sqrt(pow(a.acceleration.y, 2) + pow(a.acceleration.z, 2))) * 180/M_PI;
- Serial.print("Roll: ");
- Serial.print(roll);
- Serial.print("°\tPitch: ");
- Serial.print(pitch);
- Serial.println("°");
- delay(200);
- }
|