#include <WiFi.h>
#include <Wire.h> // Required for I2C communication with MPU6050
// Define Motor Pins
#define MOTOR1_PIN 12
#define MOTOR2_PIN 13
#define MOTOR3_PIN 14
#define MOTOR4_PIN 15
// MPU6050 Addresses and Variables
const int MPU_ADDR = 0x68; // I2C address of the MPU6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ; //Raw accelerometer and gyroscope data
// WiFi Credentials (These don't really matter in Wokwi)
const char* ssid = "Wokwi-GUEST";
const char* password = "";
void setup() {
Serial.begin(115200);
// Initialize WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
// Initialize MPU6050
Wire.begin(21, 22); // SDA, SCL (Important: Use these pins)
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
//Set up motor control pins
pinMode(MOTOR1_PIN, OUTPUT);
pinMode(MOTOR2_PIN, OUTPUT);
pinMode(MOTOR3_PIN, OUTPUT);
pinMode(MOTOR4_PIN, OUTPUT);
}
void loop() {
// Read IMU Data
Wire.beginTransmission(MPU_ADDR);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_ADDR, 14, true); // request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
// Print IMU data to serial monitor (for debugging)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.print(AcZ);
Serial.print(" | GyX = "); Serial.print(GyX);
Serial.print(" | GyY = "); Serial.print(GyY);
Serial.print(" | GyZ = "); Serial.println(GyZ);
//Basic stabilization (very simplified - THIS NEEDS A REAL PID)
int motorSpeed = map(AcX, -10000, 10000, 0, 255); //Example: Map accelerometer X to motor speed
motorSpeed = constrain(motorSpeed, 0, 255); //Keep speed within 0-255
analogWrite(MOTOR1_PIN, motorSpeed); //Control "motor" 1 based on AcX
analogWrite(MOTOR2_PIN, motorSpeed); //For now, all motors do the same thing
delay(100);
}