#include <Wire.h>
#include <Servo.h> // Include the Servo library
#include <MPU6050_tockn.h> // Include the MPU6050 library
Servo servoMotor; // Create an instance of the Servo class
MPU6050 mpu6050(Wire); // Create an instance of MPU6050
const int buttonPin = 2; // Pin connected to the pushbutton
const int photoresistorPin = A3; // Analog pin connected to the photoresistor
bool servoRotated = false; // Flag to track servo rotation
void setup() {
Serial.begin(9600); // Initialize serial communication
servoMotor.attach(9); // Attach servo to pin 9
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with internal pull-up resistor
Wire.begin(); // Initialize I2C communication
mpu6050.begin(); // Initialize MPU6050
}
void loop() {
// Read accelerometer data from MPU6050
mpu6050.update();
float ax = mpu6050.getAccX();
float ay = mpu6050.getAccY();
float az = mpu6050.getAccZ();
// Read value from photoresistor
int photoresistorValue = analogRead(photoresistorPin);
// Read state of the pushbutton
int buttonState = digitalRead(buttonPin);
// Print data to serial monitor
Serial.print("Acc: ");
Serial.print(ax);
Serial.print(", ");
Serial.print(ay);
Serial.print(", ");
Serial.print(az);
Serial.print(" | Photoresistor Value: ");
Serial.println(photoresistorValue);
// If pushbutton is pressed and servo is not rotated
if (buttonState == LOW && !servoRotated) {
servoMotor.write(180); // Rotate servo to 180 degrees
servoRotated = true; // Set flag to indicate servo rotation
delay(3000); // Wait for 3 seconds
servoMotor.write(0); // Rotate servo back to 0 degrees
delay(1000); // Wait for 1 second
servoRotated = false; // Reset flag after returning to 0 degrees
}
delay(100); // Adjust delay as needed for sampling rate
}