Motors act strangely when only motor shield is powered

I am currently using the attached 2DW Robot Chassis. 2 geared DC motors are used. I am controlling the motors with an Arduino Leonardo and a motor driver that is essentially identical to Adafruit’s Motor Driver v2.0. The issue is that when I supply power to the Arduino via either the USB cable (attached to my laptop) or via the power jack (with a 12V DC supply), the motors do what my code tells them to do. However, when I supply power to the motor shield via the power terminals using either 5, 6, or 8 AA batteries, the motors seem to just do whatever they want. They start by jerking around a little, then run continuously until I disconnect a battery. I have the VIN jumper attached to the shield, and the Arduino power LED says that it is on; it just doesn’t seem to be transferring the proper instructions, but it does when I power the Arduino and not the shield. In all cases, the power LED on the shield is on.

I have seen several sources saying it is unwise to power the Arduino and the motors using the same power source, but what other option is there for a mobile robot?

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include “utility/Adafruit_MS_PWMServoDriver.h”

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_DCMotor *leftMotor = AFMS.getMotor(1);
Adafruit_DCMotor *rightMotor = AFMS.getMotor(2);

void setup() {
AFMS.begin();
}

void stopMotors() {
leftMotor → setSpeed(0);
rightMotor → setSpeed(0);
leftMotor → run(RELEASE);
rightMotor → run(RELEASE);
}

void loop() {
// both motors run at 50% speed for 2 seconds
leftMotor → setSpeed(128);
leftMotor → run(FORWARD);
rightMotor → setSpeed(128);
rightMotor → run(FORWARD);
delay(2000);

stopMotors();
delay(1000);

// left turn for 1 second
leftMotor → run(BACKWARD);
rightMotor → run(FORWARD);
leftMotor → setSpeed(128);
rightMotor → setSpeed(128);
delay(1000);

stopMotors();
delay(1000);

// forward again
leftMotor → setSpeed(128);
leftMotor → run(FORWARD);
rightMotor → setSpeed(128);
rightMotor → run(FORWARD);
delay(2000);

stopMotors();
delay(1000);

// rotate right at 25% speed
leftMotor → run(FORWARD);
rightMotor → run(BACKWARD);
leftMotor → setSpeed(64);
rightMotor → setSpeed(64);
delay(2000);

stopMotors();
delay(1000);

}

Inputs that are undefined cause unexpected things to happen.

The best approach is to power the Arduino and the motor driver separately, but switch them on at the same time. You can buy double pole switches for that purpose.

Or use some huge capacitors.

Just power the Arduino separately so it doesn't crash all the time when the main traction battery runs low... You'll have a much less frustrating time and the thing won't go haywire at random. That's a very sensible option.