ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Embedded / IoT > I2C 버스를 통한 MPU6050 6축 자이로 센서 데이터 취득 및 상보 필터(Complementary Filter)MPU6050 6-Axis IMU Data Acquisition over I2C and Complementary Filtering
Embedded / IoT Intermediate Arduino / ESP32 Wire Library

I2C 버스를 통한 MPU6050 6축 자이로 센서 데이터 취득 및 상보 필터(Complementary Filter)MPU6050 6-Axis IMU Data Acquisition over I2C and Complementary Filtering

가속도계의 고주파 진동 노이즈와 자이로스코프의 저주파 적분 드리프트(Drift)를 상보 필터로 결합하여 롤(Roll)·피치(Pitch) 자세각을 안정적으로 추정하는 펌웨어 알고리즘입니다.A firmware algorithm that fuses high-frequency accelerometer noise with low-frequency gyroscope drift using a complementary filter to estimate Roll and Pitch angles accurately.

#Embedded #I2C #MPU6050 #Sensor #Robotics
핵심 개념가속도 센서는 외부 충격과 진동(고주파 노이즈)에 민감하지만 장기적인 중력 벡터 기준선이 일정하고, 자이로 센서는 단기 회전 반응이 빠르지만 시간 적분 오차가 누적되어 각도가 서서히 흐르는 드리프트(저주파 오차)가 발생합니다. 두 센서를 $\theta = \alpha(\theta + \omega \cdot dt) + (1 - \alpha)\theta_{\text{acc}}$ ($\alpha \approx 0.96$) 상보 필터로 합성하면 연산량이 제한된 MCU에서도 안정적인 자세각을 추정할 수 있습니다.
Key ConceptAccelerometers provide a stable long-term gravity reference but suffer from high-frequency vibration noise, whereas gyroscopes respond quickly to angular velocity but accumulate integration drift over time. Fusing both sensors with a Complementary Filter—$\theta = \alpha(\theta + \omega \cdot dt) + (1 - \alpha)\theta_{\text{acc}}$ ($\alpha \approx 0.96$)—yields stable attitude estimates with minimal CPU overhead.

1. 상보 필터 각도 추정 C++ 코드1. Complementary Filter Attitude Estimation in C++

mpu6050_complementary.ino
#include <Wire.h>
#include <math.h>

const int MPU_ADDR = 0x68;
float pitch = 0.0f;
uint32_t lastMicros = 0;

void setup() {
    Wire.begin(21, 22);    // ESP32 I2C 기본 핀: SDA=21, SCL=22
    Wire.setClock(400000); // 400kHz Fast-Mode I2C 클럭 설정

    Wire.beginTransmission(MPU_ADDR);
    Wire.write(0x6B);      // PWR_MGMT_1 전원 관리 레지스터
    Wire.write(0x00);      // 슬립 모드 해제
    Wire.endTransmission(true);
    lastMicros = micros();
}

void loop() {
    // 0x3B(ACCEL_XOUT_H)부터 가속도(6B) + 온도(2B) + 자이로(6B) 총 14바이트 버스트 읽기
    Wire.beginTransmission(MPU_ADDR);
    Wire.write(0x3B);
    Wire.endTransmission(false); // Repeated Start 유지
    Wire.requestFrom(MPU_ADDR, 14, true);

    int16_t ax = (Wire.read() << 8) | Wire.read();
    int16_t ay = (Wire.read() << 8) | Wire.read();
    int16_t az = (Wire.read() << 8) | Wire.read();
    Wire.read(); Wire.read(); // 온도 레지스터 2바이트 건너뜀
    int16_t gx = (Wire.read() << 8) | Wire.read();
    int16_t gy = (Wire.read() << 8) | Wire.read();
    int16_t gz = (Wire.read() << 8) | Wire.read();

    // 가속도 벡터 기반 절대 피치 각도(도 단위) 및 자이로 Y축 각속도(deg/s, ±250dps 기준 131 LSB)
    float accPitch  = atan2f((float)-ax, sqrtf((float)ay * ay + (float)az * az)) * (180.0f / M_PI);
    float gyroRateY = (float)gy / 131.0f;

    uint32_t now = micros();
    float dt = (now - lastMicros) * 1e-6f;
    lastMicros = now;

    // 상보 필터 결합 (자이로 단기 적분 96% + 가속도 중력 보정 4%)
    pitch = 0.96f * (pitch + gyroRateY * dt) + 0.04f * accPitch;
}
mpu6050_complementary.ino
#include <Wire.h>
#include <math.h>

const int MPU_ADDR = 0x68;
float pitch = 0.0f;
uint32_t lastMicros = 0;

void setup() {
    Wire.begin(21, 22);    // ESP32 default I2C pins: SDA=21, SCL=22
    Wire.setClock(400000); // 400kHz Fast-Mode I2C clock

    Wire.beginTransmission(MPU_ADDR);
    Wire.write(0x6B);      // PWR_MGMT_1 power management register
    Wire.write(0x00);      // Wake up from sleep mode
    Wire.endTransmission(true);
    lastMicros = micros();
}

void loop() {
    // Burst-read 14 bytes starting at 0x3B (ACCEL_XOUT_H): Accel(6B) + Temp(2B) + Gyro(6B)
    Wire.beginTransmission(MPU_ADDR);
    Wire.write(0x3B);
    Wire.endTransmission(false); // Send Repeated Start
    Wire.requestFrom(MPU_ADDR, 14, true);

    int16_t ax = (Wire.read() << 8) | Wire.read();
    int16_t ay = (Wire.read() << 8) | Wire.read();
    int16_t az = (Wire.read() << 8) | Wire.read();
    Wire.read(); Wire.read(); // Skip 2-byte temperature register
    int16_t gx = (Wire.read() << 8) | Wire.read();
    int16_t gy = (Wire.read() << 8) | Wire.read();
    int16_t gz = (Wire.read() << 8) | Wire.read();

    // Compute accelerometer pitch (deg) and Y-axis gyro rate (deg/s at ±250dps -> 131 LSB/deg/s)
    float accPitch  = atan2f((float)-ax, sqrtf((float)ay * ay + (float)az * az)) * (180.0f / M_PI);
    float gyroRateY = (float)gy / 131.0f;

    uint32_t now = micros();
    float dt = (now - lastMicros) * 1e-6f;
    lastMicros = now;

    // Complementary filter fusion (96% short-term gyro integration + 4% accelerometer gravity reference)
    pitch = 0.96f * (pitch + gyroRateY * dt) + 0.04f * accPitch;
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 초기 정지 상태 자이로 영점(Bias) 캘리브레이션: MPU6050은 센서마다 정지 상태에서도 수 deg/s 수준의 영점 오프셋을 가집니다. 부팅 직후 약 500~1,000회 샘플의 평균값을 구해 매 프레임 gx, gy, gz에서 빼주어야 초기 드리프트를 크게 줄일 수 있습니다.
  • 14바이트 연속 버스트 읽기(Burst Read) 및 400kHz 클럭 설정: 가속도와 자이로 레지스터를 개별 트랜잭션으로 따로 읽으면 I2C 주소 전송 오버헤드가 커지고 샘플 간 시점 불일치가 발생합니다. Wire.setClock(400000)으로 Fast-Mode를 켜고 0x3B부터 14바이트를 한 번에 읽는 것이 효율적입니다.
  • Yaw(방위각) 축의 중력 보정 한계: 중력 벡터는 지면과 수직이므로 Roll과 Pitch 기울기는 보정할 수 있지만, 지면과 수평으로 회전하는 Yaw 축은 가속도계로 보정할 수 없습니다. Yaw 드리프트까지 잡으려면 지자기 센서(9축 IMU)나 내장 DMP 쿼터니언 출력을 활용해야 합니다.
  • Calibrate Stationary Gyroscope Zero-Offset at Boot: Every MEMS gyroscope exhibits a small zero-rate bias while stationary. Average 500–1,000 samples while the device is flat at startup and subtract those offsets from raw gx, gy, gz readings on every loop.
  • Use 14-Byte Burst Reads at 400kHz I2C: Enabling Fast-Mode (Wire.setClock(400000)) and reading all 14 sensor bytes in a single repeated-start transaction starting at 0x3B minimizes bus latency and guarantees that accelerometer and gyroscope samples belong to the same time slice.
  • Yaw Axis Drift Cannot Be Corrected by Gravity Alone: Because the gravity vector points vertically, an accelerometer can correct Roll and Pitch tilt but cannot observe horizontal Yaw rotation. Preventing Yaw drift requires a 9-axis magnetometer or visual/wheel odometry.

I2C 14바이트 버스트 리드와 1차 상보 필터 수식을 결합하면, 행렬 연산이 무거운 칼만 필터를 구현하지 않고도 수 줄의 부동소수점 연산만으로 반응성이 빠른 기울기 추정기를 구성할 수 있습니다.

Pairing a 14-byte I2C burst read with a first-order complementary filter provides responsive, drift-compensated tilt estimation in just a few lines of floating-point math.