MPU6050

ESP32에서 MPU6050을 i²c방식으로 읽어서, pitch, roll 값으로 보여주는 코드

MPU6050.ino
//
// MPU6050을 읽어서, pitch, roll 값으로 보여주는 코드
// 
#include <Wire.h>
 
#define MPU6050_ADDR 0x68
 
void setup() {
  Serial.begin(115200);
  Wire.begin(21, 22);   // SDA=21, SCL=22 (ESP32 기본)
 
  // MPU6050 깨우기 (Sleep 해제)
  Wire.beginTransmission(MPU6050_ADDR);
  Wire.write(0x6B);   // 전원 관리 레지스터
  Wire.write(0);      // 0 → sleep 해제
  Wire.endTransmission(true);
}
 
void loop() {
  Wire.beginTransmission(MPU6050_ADDR);
  Wire.write(0x3B);  // ACCEL_XOUT_H (데이터 시작 주소)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU6050_ADDR, 14, true); // 가속도+온도+자이로 14바이트
 
  int16_t ax = Wire.read() << 8 | Wire.read();
  int16_t ay = Wire.read() << 8 | Wire.read();
  int16_t az = Wire.read() << 8 | Wire.read();
  int16_t temp = Wire.read() << 8 | Wire.read();
  int16_t gx = Wire.read() << 8 | Wire.read();
  int16_t gy = Wire.read() << 8 | Wire.read();
  int16_t gz = Wire.read() << 8 | Wire.read();
 
  float AccX = ax / 16384.0;  
  float AccY = ay / 16384.0;
  float AccZ = az / 16384.0;
 
  float pitch = atan2(-AccX, sqrt(AccY * AccY + AccZ * AccZ)) * 180 / PI;
  float roll  = atan2(AccY, AccZ) * 180 / PI;
 
  Serial.print("Pitch: "); Serial.print(pitch);
  Serial.print("°, Roll: "); Serial.println(roll);
 
  delay(100);
}