Error: Arduino not working from external power source.


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);

int sensorReading(int trigPin, int echoPin)
  digitalWrite(trigPin, LOW); 

  digitalWrite(trigPin, HIGH);
  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" */
    return -1;
  else {
  /* Send the distance to the computer using Serial protocol, and
  turn LED OFF to indicate successful reading. */
    return distance;

void loop() 
    if(sensorReading(trigPinF, echoPinF) <= 7 && sensorReading(trigPinF, echoPinF) != -1)
  digitalWrite(3, HIGH);

Please help!

Best regards,

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.