#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <Stepper.h>
Adafruit_MPU6050 mpu;
float stepmax = 600; // Define maximum steps per revolution for stepper motor
Stepper myStepper(stepmax, 12, 14, 27, 26); // Initialize Stepper library with pins 12, 14, 27, 26
void setup(void) {
Serial.begin(115200); // Start serial communication at 115200 baud rate
myStepper.setSpeed(30); // Set the speed of the motor in RPM
// Initialize MPU6050 sensor
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) { // Loop if initializtion fails
delay(10);
}
}
// Configure MPU6050 settings for accelerometer and gyro range, and filter bandwidth
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
mpu.setGyroRange(MPU6050_RANGE_250_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.println("MPU6050 initialization successful");
delay(1000); // Short delay for calibration
}
void loop() {
// Variables to hold sensor event data
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp); // Fetch the latest data from the MPU6050 sensor
// Print accelerometer values to the Serial Monitor
Serial.print("Accelerometer: X: ");
Serial.print(a.acceleration.x);
Serial.print(" Y: ");
Serial.print(a.acceleration.y);
Serial.print(" Z: ");
Serial.println(a.acceleration.z);
// Print gyroscope values to the Serial Monitor
Serial.print("Gyroscope: X: ");
Serial.print(g.gyro.x);
Serial.print(" Y: ");
Serial.print(g.gyro.y);
Serial.print(" Z: ");
Serial.println(g.gyro.z);
int steps = 10; // Define a fixed number of steps for demo
if (g.gyro.x > 0) {
// If gyroscope X-axis reading is positive, rotate the stepper motor in one direction
myStepper.step(steps);
Serial.println("Moving FORWARD"); // Indicate movement direction
} else if (g.gyro.x < 0) {
// If gyroscope X-axis reading is negative, rotate the stepper motor in the opposite direction
myStepper.step(-steps);
Serial.println("Moving BACKWARD"); // Indicate movement direction
}
delay(100);
}