Reviewing a code

Balancing code for a drone

#define motor_FL 8 // front left motor
#define motor_FR 9 //front right motor
#define motor_BL 12 //back left motor
#define motor_BR 13 //back right motor
#include <Wire.h>
#include <MPU6050.h>
MPU6050 gy_521;
int16_t ax, ay, az;
int16_t gx, gy, gz;
int command;
int DSPEED = 155;
int DSPEEDA;
int DSPEEDB;
int DSPEEDC;
int DSPEEDD;

void setup() {

pinMode(motor_FL, OUTPUT);
pinMode(motor_FR, OUTPUT);
pinMode(motor_BL, OUTPUT);
pinMode(motor_BR, OUTPUT);
Wire.begin( );
Serial.begin (9600);
Serial.println (“Initializing MPU and testing connections”);
gy_521.initialize ( );
Serial.println(gy_521.testConnection( ) ? “Successfully Connected” : “Connection failed”);
delay(1000);
Serial.println(“Reading Values”);
delay(1000);
}

void loop(){
Balancing();}

void Balancing(){
gy_521.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
ax = map(ax, -17000, 17000, -55, 55);
DSPEEDB = DSPEED+ax; //if tilted to x+ side FR and BR increase
DSPEEDD = DSPEED+ax;

DSPEEDA = DSPEED-ax; //if tilted to x- side FL and BL increase
DSPEEDC = DSPEED-ax;

ay = map(ay, -17000, 17000, -55, 55);
DSPEEDA = DSPEED+ax; // if tilted to y+ side FL and FR increase
DSPEEDB = DSPEED+ax;

DSPEEDC = DSPEED-ax; //if tilted to y- side BL and BR increase
DSPEEDD = DSPEED-ax;

analogWrite (motor_FL, DSPEEDA);
analogWrite (motor_FR, DSPEEDB);
analogWrite (motor_BL, DSPEEDC);
analogWrite (motor_BR, DSPEEDD);
delay (200);
}

To make it easy for people to help you please modify your post and use the code button </> so your code looks like this and is easy to copy to a text editor. See How to use the Forum

What happens when you run your program? What does it actually do and what do you want it to do that is different?

What is the machine that you are trying to balance? The nature of the motors and the size, mass, and inertia of the machine are all an important part of getting the system to work.

I would be very surprised if any balancing code will work if it uses the delay() function as it blocks the Arduino from doing other things. The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking. It may help with understanding the technique.

Have a look at Using millis() for timing. A beginners guide if you need more explanation.

…R

And PID
If you want to make a system stable, PID is a must.
Go read up about it.

I wonder why people do this - unless for the challenge - it’s a complex task , yet dedicated controllers with built in gyro’s are very cheap , have had a lot of development and work very well.

If you are using an Arduino UNO, you have to use pins 3, 5, 6, 9, 10, or 11 for analogWrite(). You should probably mention what board you are using if you want help with your sketch.