// Include necessary libraries for OLED, MPU6050, and I2C communication
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
// Define OLED screen dimensions
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Create OLED display object connected to I2C
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// Create MPU6050 object for sensor operations
Adafruit_MPU6050 mpu;
void setup(void) {
// Start serial communication at 9600 baud rate
Serial.begin(9600);
// Initialize the OLED display
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
// Print error message if OLED initialization fails
Serial.println(F("failed to start SSD1306 OLED"));
// Infinite loop to halt execution
while (1);
}
// Clear any previous content on the OLED display
oled.clearDisplay();
// Set text size for OLED display
oled.setTextSize(1);
// Set text color for OLED display
oled.setTextColor(WHITE);
// Initialize the MPU6050 sensor
if (!mpu.begin()) {
// Print error message if MPU6050 initialization fails
Serial.println("Failed to find MPU6050 chip");
// Infinite loop to halt execution
while (1) {
delay(10);
}
}
// Set accelerometer range to 8G
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
// Set gyroscope range to 250 degrees per second
mpu.setGyroRange(MPU6050_RANGE_250_DEG);
// Set filter bandwidth to 21Hz
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
// Wait for 1 second before starting the main loop
delay(1000);
}
void loop() {
// Create sensor event objects for accelerometer, gyroscope, and temperature
sensors_event_t a, g, temp;
// Get sensor readings
mpu.getEvent(&a, &g, &temp);
// Clear the OLED display for fresh data
oled.clearDisplay();
// Set cursor position and print accelerometer data label
oled.setCursor(0, 0);
oled.println("Accelerometer:");
oled.setCursor(0, 10);
oled.print(a.acceleration.x/10, 2);
oled.print(",");
oled.print(a.acceleration.y/10, 2);
oled.print(",");
oled.println(a.acceleration.z/10, 2);
// Set cursor position and print gyroscope data label
oled.setCursor(0, 30);
oled.println("Gyroscope:");
oled.setCursor(0, 40);
oled.print(g.gyro.x/10, 2);
oled.print(",");
oled.print(g.gyro.y/10, 2);
oled.print(",");
oled.println(g.gyro.z/10, 2);
// Update the OLED display with new data
oled.display();
// Wait for 0.5 seconds before the next loop iteration
delay(500);
}