Robot working with usb but only sometimes with battery

Using this motor

 //Motortest med fire DC motorer

const int LED_PIN = 13;
const int speed1  = 100; // percent maximum speed

#define echoPin A5
#define trigPin A4

int maximumRange = 200;
int minimumRange = 0;
long duration, distance;

#include <AFMotor.h> //adafruit motor shield library
AF_DCMotor Motor_Left_Front(4, MOTOR34_1KHZ); // Motor 4
AF_DCMotor Motor_Right_Front(3, MOTOR34_1KHZ); // Motor 3
AF_DCMotor Motor_Left_Rear(1, MOTOR34_1KHZ); // Motor 1
AF_DCMotor Motor_Right_Rear(2, MOTOR34_1KHZ); // Motor 2
int pwm;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
  
  // scale percent into pwm range (0-255)
  pwm = map(speed1, 0, 100, 0, 255);
  Motor_Left_Front.setSpeed(pwm);
  Motor_Right_Front.setSpeed(pwm);
  Motor_Left_Rear.setSpeed(pwm);
  Motor_Right_Rear.setSpeed(pwm);
}
// run over and over
void loop() {
  digitalWrite(trigPin,LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin,HIGH);

  delayMicroseconds(10);
  digitalWrite(trigPin,LOW);
  duration = pulseIn(echoPin,HIGH);
  distance = (duration/2) / 29.1;

  if (distance>=20){
  // put your main code here, to run repeatedly:+
  Serial.println("rotate cw");

  Motor_Left_Front.run(FORWARD);
  Motor_Left_Rear.run(FORWARD);
  Motor_Right_Front.run(FORWARD);
  Motor_Right_Rear.run(FORWARD);
  }
  else{
    
    Motor_Left_Front.run(BACKWARD);
    Motor_Left_Rear.run(FORWARD);
    Motor_Right_Front.run(BACKWARD);
    Motor_Right_Rear.run(FORWARD);
  }
                                                                                                   
  /*delay(5000); // run for 5 seconds
  
 
  Serial.println("stopped");
  Motor_Left_Front.run(RELEASE); // stop the motors
  Motor_Right_Front.run(RELEASE);
  Motor_Left_Rear.run(RELEASE); // stop the motors
  Motor_Right_Rear.run(RELEASE);
  delay(5000); // stop for 5 seconds
 */
}

this is my code

so with battery it will just only drive sometimes… cant figure out why… i have tried to change battery and the uno board but it wont work… you guys are my last hope :smiley:

just ignore the wire that got loose from the one wheel… gonna fix that while im writing this… but when the wire is ACTUALLY CONNECTED TO THE WHEEL i still have problems

You seem to have omitted the important information - what battery are you using?

Or do I see the end of a PP3 style smoke-alarm battery? If so, they are completely unsuitable - they can't provide enough current. Try a pack of 6 x AA alkaline cells

...R

im using a 9v energizer industrial battery :slight_smile:
is that suitable?

wafflewolf:
im using a 9v energizer industrial battery :slight_smile:
is that suitable?

From the symptoms you describe, NO.

...R