doing different things when plugged in to computer and power supply

when plugged into the computer the arduino mega 2560 does exactly what i tells it to how ever when plugged into power supply it does not get correct ultrasonic sensor readings and starts only doing the if statement. do i need more power?

code:

#include <AFMotor.h>
#include <NewPing.h>

#define trigPin 24
#define echoPin 36

AF_DCMotor motor(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);

void setup() {

Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

}

void loop() {

motor.run(FORWARD);
motor2.run(FORWARD);
motor.setSpeed(90);
motor2.setSpeed(90);

int duration, distance;

digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
Serial.print(distance);
Serial.println(" cm");
delay(500);

if (distance >= 20 || distance <= 0){

}else{
motor.run(RELEASE);
motor2.run(RELEASE);
delay(1500);
motor.setSpeed(250);
motor2.setSpeed(250);
motor.run(BACKWARD);
motor2.run(BACKWARD);
delay(400);
motor2.run(FORWARD);
delay(750);
motor2.run(RELEASE);
motor.run(RELEASE);
delay(500);
}
}

Post the code using code tags in future.
In this case the code has absoloutly nothing to do with your problem.
You have a hardware problem probbly caused by the lack of a common ground.

so what should i do should i give it more power or less power

No you fix the grounding problem.
You have hardly given us anything to work on.
Concentration the differences between the external power and USB power.
Tell us what your set up is, and what the rating of your power supply is and how you have connected it up.

i have a autonomous robot with 1 ping sensor and 2 7.2 rc batteries at 2400mah and a fuse for the arduino with a power supply also going to the adafruit motor shield and 2 dc motors i cut a usb cable open to power the arduino mega that is coonected to the fuse to one of the batteries

battery 1-----switch-----fuse-----usb-----mega
|
battery 2-----switch------------------------motorshield

basic diagram

Sorry but that is simply not enough information to tell anything.
For example where are the grounds going?

what do you mean?

I mean that the so called diagram tells absoloutly nothing.
If you are not going to provide any meaningfully information then no one can help you.

ping sensor on 24 echo and 36 trigger does that help other than that there is no schimatic

unknown3083:
ping sensor on 24 echo and 36 trigger does that help other than that there is no schimatic

Then no one can help you.

:disappointed_relieved: the shield is an adafruit motor shield that is all i have and the arduino mega and two dc motors on motor 1 and 2 with battery connected to motor shield

Hi, its time for a circuit diagram please, the main question is, are all the negative terminals of the power supplies and arduino connected together.
But a circuit diagram will be of great assistance.
Tom.