Difficulty Level: Intermediate
This tutorial demonstrates how to perform sensor fusion using a gyroscope and an accelerometer with an ESP32. The aim is to calculate the orientation of the device more accurately by combining data from both sensors.
Connect the MPU6050 to the ESP32 as follows:
The following code reads data from the MPU6050 and combines the accelerometer and gyroscope data to compute the orientation of the device using complementary filtering.
Wire.begin()
: Initializes the I2C communication.mpu.initialize()
: Initializes the MPU6050 sensor.mpu.getMotion6()
: Reads the accelerometer and gyroscope data.atan2()
: Computes the angle based on the accelerometer data.filter()
: Applies complementary filtering to fuse the accelerometer and gyroscope data.Here’s the Arduino code for the multi-sensor fusion:
#include
#include
MPU6050 mpu;
float ax, ay, az; // Accelerometer readings
float gx, gy, gz; // Gyroscope readings
float angleX = 0, angleY = 0; // Angles
const float alpha = 0.98; // Complementary filter constant
void setup() {
Serial.begin(115200);
Wire.begin();
mpu.initialize();
}
void loop() {
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// Convert accelerometer readings to angles
float accelAngleX = atan2(ay, az) * 180 / PI;
float accelAngleY = atan2(ax, az) * 180 / PI;
// Complementary filter
angleX = alpha * (angleX + gx * 0.01) + (1 - alpha) * accelAngleX;
angleY = alpha * (angleY + gy * 0.01) + (1 - alpha) * accelAngleY;
// Print the angles
Serial.print("Angle X: "); Serial.print(angleX);
Serial.print(" | Angle Y: "); Serial.println(angleY);
delay(10);
}
In this tutorial, you learned how to use a gyroscope and accelerometer to calculate the orientation of a device using sensor fusion techniques. The complementary filter combines the strengths of both sensors for accurate angle measurements.