MPU-6050-gy521-arduino-servo

Hello friends! Hope you are enjoying our projects..here is one more project.. In this article you can see the video demo to control servo with using GY-521 (MPU-6050) and Arduino Uno.

Arduino code for MPU6050

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

MPU6050 mpu;

Servo servoMotor;

void setup() {
  Serial.begin(9600);

  // Initialize MPU6050
  Wire.begin();
  mpu.initialize();

  // Attach the servo to pin 9
  servoMotor.attach(9);
}

void loop() {
  // Read MPU6050 data
  int16_t gyroX, gyroY, gyroZ;
  mpu.getRotation(&gyroX, &gyroY, &gyroZ);

  // Convert gyro values to degrees per second
  float gyroXangle = gyroX / 131.0;
  float gyroYangle = gyroY / 131.0;

  // Use the gyro angle to control the servo
  int servoPosition = map(gyroYangle, -90, 90, 0, 180);
  servoMotor.write(servoPosition);

  // Print gyro values and servo position
  Serial.print("Gyro X: ");
  Serial.print(gyroXangle);
  Serial.print(" degrees/s, Gyro Y: ");
  Serial.print(gyroYangle);
  Serial.print(" degrees/s, Servo Position: ");
  Serial.println(servoPosition);

  delay(20);  // Adjust the delay as needed for your application
}
9 Comments
  1. mubin mahadhir 7 years ago
    WordPress › Error

    There has been a critical error on this website.

    Learn more about troubleshooting WordPress.