Error: Arduino not working from external power source.

Hello.

I want to make maze robot with pladge algorithm. I wrote just simple test program for it. It works fine if I am connected to computer, but if I want to power arduino from 9v battery then it does some kind of madness. I have modified servos so I control motors like servos. I use two sonars HC SR-04. Code is here:

//maze robot code by: Mikk Kruusalu

#include <Servo.h>

Servo rightServo;
Servo leftServo;

#define echoPinF 13 // Echo Pin
#define trigPinF 12 // Trigger Pin
#define echoPinR 5
#define trigPinR 6

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

const int sensorfVCC = 11;
const int sensorrVCC = 4;
const int servoVCC = 8;

int counter = 0;

void setup() {
  Serial.begin (9600);
  
  pinMode(sensorfVCC, OUTPUT);
  pinMode(servoVCC, OUTPUT);
  pinMode(sensorrVCC, OUTPUT);
  digitalWrite(sensorrVCC, HIGH);
  digitalWrite(servoVCC, HIGH);
  digitalWrite(sensorfVCC, HIGH);
  
  pinMode(3, HIGH);
  
  pinMode(trigPinR, OUTPUT);
  pinMode(echoPinR, INPUT);
  pinMode(trigPinF, OUTPUT);
  pinMode(echoPinF, INPUT);
  
  rightServo.attach(9);
  leftServo.attach(10);
}

int sensorReading(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); 
 
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
 
  //Calculate the distance (in cm) based on the speed of sound.
  distance = duration/58.2;
 
  if (distance >= maximumRange || distance <= minimumRange){
  /* Send a negative number to computer and Turn LED ON 
  to indicate "out of range" */
    Serial.println("-1");
    return -1;
  }
  else {
  /* Send the distance to the computer using Serial protocol, and
  turn LED OFF to indicate successful reading. */
    Serial.println(distance);
    return distance;
  }
}

void loop() 
{
  while(true)
  {
    leftServo.write(180);
    rightServo.write(70);
    if(sensorReading(trigPinF, echoPinF) <= 7 && sensorReading(trigPinF, echoPinF) != -1)
    {
      leftServo.write(0);
      rightServo.write(70);
      delay(610);
    }
  }
  
  digitalWrite(3, HIGH);
}

Please help!

Best regards,
Mikk
Contact: kruusalu.mikk@gmail.com

but if I want to power arduino from 9v battery then it does some kind of madness.

Because a 9V battery is pathetic. You need a REAL battery, not some wimpy-ass low-current smoke detector battery. Unless you have a smoke detector, that is.

Thanks! I don't know why I didn't figured it out myself :). Everything is working now.