Sensor Fusion with ESP32

Multi-Sensor Fusion with Gyroscope and Accelerometer

Multi-Sensor Fusion Using Gyroscope and Accelerometer

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.

Required Components with eBay Links

Wiring the MPU6050

Connect the MPU6050 to the ESP32 as follows:

Code Explanation

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.

Key Functions

Arduino Code

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);
}
            

Upload and Test

  1. Connect your ESP32 to your computer using the USB cable.
  2. Open the Arduino IDE and copy the code above into the editor.
  3. Select your ESP32 board and the correct port in the IDE.
  4. Click the upload button to send the code to the ESP32.
  5. Open the Serial Monitor to view the calculated angles.

Conclusion

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.