Self balancing robot

Hey guys. I have made a self balancing robot now. The problem is:
When connected with the battery and made to run, runs for a few seconds and the input from the
MPU6050 gets random. I suspect this is because of the vibration of the motor causing the wires to connect
and disconnect, because if i connect to the computer it runs properly.

Can anyone identify the problem

my code if necessary, i thing the problem might be in the hardware

#include <Wire.h>
const int MPU_addr=0x68; 
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
int minVal=265; int maxVal=402;
double x;         //A4 (SDA), A5 (SCL)
double y; 
double z;
int lmt1=6;
int lmt2=5;
int rmt1=9;
int rmt2=10;
int value;

void setup(){
  pinMode(lmt1,OUTPUT);
  pinMode(lmt2,OUTPUT);
  pinMode(rmt1,OUTPUT);
  pinMode(rmt2,OUTPUT);
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B); Wire.write(0);
Wire.endTransmission(true);
Serial.begin(9600); } 

void loop(){ 
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
Wire.endTransmission(false); 
Wire.requestFrom(MPU_addr,14,true);
AcX=Wire.read()<<8|Wire.read(); 
AcY=Wire.read()<<8|Wire.read();
AcZ=Wire.read()<<8|Wire.read(); 
int xAng = map(AcX,minVal,maxVal,-90,90);
int yAng = map(AcY,minVal,maxVal,-90,90);
int zAng = map(AcZ,minVal,maxVal,-90,90);

x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);
//---------------------------------------------- This part of the program is
//                                                            just to convert the angle from the gyro (0-360)
//                                                            into -180 to 180
if(y>180){
y=y-360;
}
if(y<180){
}
//--------------------------------------------- back tilt response
if(y>0)//backward tilt +
{
  value=map(y,0,45,50,255);
  analogWrite(lmt1,value);
  analogWrite(lmt2,0);
  analogWrite(rmt1,value);
  analogWrite(rmt2,0);
  Serial.print("b   ");
}
//---------------------------------------------- front tilt response
if(y<0)//forward tilt -
{
  y=y*-1;
  value=map(y,0,45,50,255);
  analogWrite(lmt1,0);
  analogWrite(lmt2,value);
  analogWrite(rmt1,0);
  analogWrite(rmt2,value);
}
Serial.print(y);
Serial.print("    ");
Serial.println(value);
}

and i understand i should be using PID algorithm to balance the robot but for now this

Well, then check the hardware first.

All hardware works fine. Just checked.

But when connected using the battery the problem occurs.

Guess: Batty too weak.