#include <Wire.h>
#include <MPU6050.h>
#include <DHT.h>

// Define DHT22 sensor settings
#define DHTPIN 2        // Digital pin for DHT22
#define DHTTYPE DHT22   // DHT22 type
DHT dht(DHTPIN, DHTTYPE);

// Create an MPU6050 object
MPU6050 mpu;

void setup() {
  // Initialize serial communication
  Serial.begin(9600);
  
  // Initialize DHT22 sensor
  dht.begin();
  Serial.println("DHT22 sensor initialized");

  // Initialize I2C for MPU6050 sensor
  Wire.begin();
  mpu.initialize();

  // Check if the MPU6050 is connected properly
  if (mpu.testConnection()) {
    Serial.println("MPU6050 connection successful");
  } else {
    Serial.println("MPU6050 connection failed");
    while (1); // Halt if the sensor can't be initialized
  }
}

void loop() {
  // Reading DHT22 data (temperature and humidity)
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

  // Check if any readings failed
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT22 sensor!");
  } else {
    // Print DHT22 sensor data
    Serial.print("Humidity: ");
    Serial.print(humidity);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");
  }

  // Read raw values from MPU6050
  int16_t accX, accY, accZ, gyroX, gyroY, gyroZ;
  mpu.getAcceleration(&accX, &accY, &accZ);
  mpu.getRotation(&gyroX, &gyroY, &gyroZ);

  // Convert raw values to meaningful data
  Serial.print("Accel (raw) -> X: ");
  Serial.print(accX);
  Serial.print(" Y: ");
  Serial.print(accY);
  Serial.print(" Z: ");
  Serial.println(accZ);

  Serial.print("Gyro (raw) -> X: ");
  Serial.print(gyroX);
  Serial.print(" Y: ");
  Serial.print(gyroY);
  Serial.print(" Z: ");
  Serial.println(gyroZ);

  // Delay between readings for readability
  delay(2000);
}