I'm trying to control servomotors by using (gyrosensor) MPU-6050. It actually works fine, but the problem is that everytime I connect a servo to the sensor, the servo rotates all the way (to its most "extreme" position). What I would like it to do is for the servo to move to its center position when connected to MPU-6050. Do you guys have any idea how to do this. This is the code I'm using. (source for the code)
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include <Servo.h>
Servo servo1;
Servo servo2;
Servo servo3;
MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;
//Usado para calcular o angulo - Variaveis do acelerometro
double accXangle;
double accYangle;
double accZangle;
//Usado para calcular o angulo - Variaveis do giroscopio
double gyroXangle = 180;
double gyroYangle = 180;
double gyroZangle = 180;
uint32_t timer;
void setup() {
Wire.begin();
// Inicializando a comunicação serial
// funciona em 8MHz ou em 16MHz
Serial.begin(38400);
// Iniciando dispositivos
Serial.println("Inicializando cominicação I2C...");
accelgyro.initialize();
// Testando a conexão com a MPU6050
Serial.println("Testando a conexão com MPU6050...");
Serial.println(accelgyro.testConnection() ? "MPU6050 conectada com sucesso" : "Falha na conexão com a MPU6050");
servo1.attach(12);
servo2.attach(10);
servo3.attach(9);
timer = micros();
}
void loop() {
// Fazendo a leitura de conexão com a MPU6050
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// Calcular os angulos com base nos sensores do acelerometro
accXangle = (atan2(ax,az) + PI) * RAD_TO_DEG;
accYangle = (atan2(ay,az) + PI) * RAD_TO_DEG;
accZangle = (atan2(ax,ay) + PI) * RAD_TO_DEG;
double gyroXrate = ((double)gx / 131.0);
double gyroYrate = -((double)gy / 131.0);
double gyroZrate = -((double)gz / 131.0);
//###################### Calcular o ângulo de giro sem qualquer filtro #########################
gyroXangle += gyroXrate*((double)(micros()-timer)/1000000);
gyroYangle += gyroYrate*((double)(micros()-timer)/1000000);
gyroZangle += gyroZrate*((double)(micros()-timer)/1000000);
servo1.write(gyroYangle);
servo2.write(gyroXangle);
servo3.write(gyroZangle);
timer = micros();
// A taxa de amostras máxima do acelerometro é de 1KHz
delay(1);
// //Tabela Separada para os valores accel/gyro x/y/z values
// Serial.print("a/g:\t");
// Serial.print(ax); Serial.print("\t");
// Serial.print(ay); Serial.print("\t");
// Serial.print(az); Serial.print("\t");
// Serial.print(gx); Serial.print("\t");
// Serial.print(gy); Serial.print("\t");
// Serial.println(gz);
//Angulo Giroscopio x/y/z
Serial.print(gyroXangle); Serial.print("\t");
Serial.print(gyroYangle); Serial.print("\t");
Serial.print(gyroZangle); Serial.print("\t");
Serial.print("\n");
}