CodeHub
HomeUploadContact
Back to Hub

mpu6050 controlled Servo motor

April 8, 2026 Watch Tutorial

Wiring Schematic

mpu6050 controlled Servo motor wiring diagram

Hardware Required

  • Arduino Board
    Buy on Amazon

Source Code

Arduino / C++
1#include <Wire.h>
2#include <Servo.h>
3
4const int MPU_addr = 0x68; // Standard I2C address of the MPU-6050
5int16_t AcX, AcY, AcZ;     // Variables to store raw accelerometer data
6
7Servo myServo;
8
9void setup() {
10  Serial.begin(115200);
11  
12  // Attach the servo to Pin 9 on the Mega
13  myServo.attach(9);
14  
15  // Initialize I2C communication
16  Wire.begin();
17  
18  // Wake up the MPU-6050 
19  Wire.beginTransmission(MPU_addr);
20  Wire.write(0x6B);  // Target the Power Management register
21  Wire.write(0);     // Write a 0 to wake it up
22  Wire.endTransmission(true);
23  
24  Serial.println("MPU6050 is awake! Ready for REVERSED front/back movement.");
25
26  // Start the servo in the middle, safe position (90 degrees)
27  myServo.write(90);
28  delay(1000);
29}
30
31void loop() {
32  // Start reading from the MPU6050
33  Wire.beginTransmission(MPU_addr);
34  Wire.write(0x3B);  
35  Wire.endTransmission(false);
36  
37  // Request 6 registers total
38  Wire.requestFrom(MPU_addr, 6, true);  
39  
40  // Read the raw data 
41  AcX = Wire.read() << 8 | Wire.read();      
42  AcY = Wire.read() << 8 | Wire.read(); // Y-axis (Front-to-back) 
43  AcZ = Wire.read() << 8 | Wire.read();  
44  
45  // Constrain raw Y so it doesn't glitch 
46  int constrainedY = constrain(AcY, -17000, 17000);
47  
48  // REVERSED LOGIC: Map the Y-axis to 165 -> 15 instead of 15 -> 165
49  int servoAngle = map(constrainedY, -17000, 17000, 165, 15);
50  
51  // Move the servo safely
52  myServo.write(servoAngle);
53  
54  // Print values to the Serial Monitor 
55  Serial.print("Raw Y: ");
56  Serial.print(AcY);
57  Serial.print(" | Reversed Servo Angle: ");
58  Serial.println(servoAngle);
59  
60  // Small delay for smooth movement
61  delay(50);
62}
Servo motor
Buy on Amazon
  • Mpu6050
    Buy on Amazon
  • Jumper wires
    Buy on Amazon
  • Breadboard
    Buy on Amazon
  • USB Cable
    Buy on Amazon