I'm creating a fin control for a model rocket using Esp32 with 4 servos connected to G33,G25,G26,G27 respectively and a MPU6050 sensor SDA to G21 and SCL to G22. I'm using the esp32 just for a better processing power.
These are the connections
This is the code I'm using
#include <Wire.h>
#include <MPU6050.h>
#include <ESP32Servo.h>
Servo servo1, servo2, servo3, servo4;
int servo1Pin = 33; // Replace with the actual GPIO pin numbers
int servo2Pin = 25;
int servo3Pin = 26;
int servo4Pin = 27;
MPU6050 sensor;
void setup() {
servo1.attach(servo1Pin);
servo2.attach(servo2Pin);
servo3.attach(servo3Pin);
servo4.attach(servo4Pin);
Wire.begin();
sensor.initialize();
}
void loop() {
int16_t ax, ay, az, gx, gy, gz;
sensor.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// Map acceleration values to servo angles (0-180)
int servoAngle1 = map(ax, -17000, 17000, 0, 180);
int servoAngle2 = map(az, -17000, 17000, 0, 180);
servo1.write(servoAngle1);
servo2.write(servoAngle2);
servo3.write(180 - servoAngle1);
servo4.write(180 - servoAngle2);
delay(10); // Adjust delay as needed
}
I'm not able to understand how this code works because I got this code from Bing Copilot. To my surprise, this works pretty fine and the servos turn opposite accordingly to sensor's orientation.
My doubt is that why am I using ax and az which is acceleration instead of gx and gz which gives angular speed. The problem that would so appear will be that when rocket accelerates, servos will randomly rotate and totally break the trajectory.
Can somebody tell me what can i improve to be more precise?