#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <MPU6050.h>
#include <AccelStepper.h>
// MPU6050 Accelerometer/Gyro Sensor
MPU6050 mpu;
// Define the two buttons
const int button1Pin = 2;
const int button2Pin = 3;
// Define the stepper motor and driver pins
const int dirPin = 4;
const int stepPin = 5;
const int ms1Pin = 6;
const int ms2Pin = 7;
const int ms3Pin = 8;
const int enablePin = 9;
// Define the stepper motor and driver
AccelStepper stepper(1, stepPin, dirPin);
const int stepsPerRevolution = 200;
void setup() {
Serial.begin(9600);
// Initialize the MPU6050 sensor
mpu.initialize();
// Initialize the two buttons
pinMode(button1Pin, INPUT_PULLUP);
pinMode(button2Pin, INPUT_PULLUP);
// Initialize the stepper motor driver
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, LOW);
pinMode(ms1Pin, OUTPUT);
pinMode(ms2Pin, OUTPUT);
pinMode(ms3Pin, OUTPUT);
// Configure the A4988 driver for full-step mode
digitalWrite(ms1Pin, LOW);
digitalWrite(ms2Pin, LOW);
digitalWrite(ms3Pin, LOW);
// Initialize the stepper motor and driver
stepper.setMaxSpeed(1000);
stepper.setAcceleration(500);
stepper.setSpeed(500);
stepper.setPinsInverted(false, false, true);
stepper.moveTo(0);
}
void loop() {
// Read the orientation data from the MPU6050
int ax, ay, az;
mpu.getMotion6(&ax, &ay, &az, 0, 0, 0);
Serial.println("value of AY= ");
Serial.println(ay);
// Check if the sensor is rotated clockwise
if (ay > 500) {
// Check if button 1 is pressed
if (digitalRead(button1Pin) == LOW) {
// Stop the motor
while(ay>0){
Serial.println("value of ay= ");
Serial.println(ay);
mpu.getMotion6(&ax, &ay, &az, 0, 0, 0);
stepper.setSpeed(0);
}
} else {
// Rotate the motor clockwise
stepper.setSpeed(500);
stepper.runSpeed();
}
}
// Check if the sensor is rotated counterclockwise
if (ay < -500) {
// Check if button 2 is pressed
if (digitalRead(button2Pin) == LOW) {
// Stop the motor
while(ay<0){
Serial.println("value of ay= ");
Serial.println(ay);
mpu.getMotion6(&ax, &ay, &az, 0, 0, 0);
stepper.setSpeed(0);
}
} else {
// Rotate the motor counterclockwise
stepper.setSpeed(-500);
stepper.runSpeed();
}
}
}