Arduino runs different sketch on external power vs usb connection to laptop

Hello, I’m working on a project with some students building a simple robot with an arduino and two small continuous rotation servos.

The first sketch we created simply ran the servos for one second and then paused for one second (robot moves forward and then pauses). We subsequently tried a second sketch that drove forward two seconds and then moved the servos in opposite directions to turn the robot. When connected via usb we can upload and run the second sketch, but when we revert to external power using a 9V battery, the first sketch runs.

We can make the robot do anything we want via usb, but it always reverts to the 1 s forward and 1 s pause when running from the battery.

Could the programmer be an issue? I had been working with some students on another project and had “Arduino as ISP” set as the programmer, then changed it as we were working on the new project (I don’t recall when in the sequence).

Our circuit: 9V battery provides external power to the arduino. Two servos are connected to the 5 V power supply on the arduino and controlled via pins 9 and 10.

First sketch:

#include <Servo.h>
Servo john1;
Servo john2;

void setup() {
john1.attach(9);
john2.attach(10);
}

void loop() {
john1.write(180);
john2.write(0);
delay(1000);
john1.write(90);
john2.write(90);
}

The second sketch is identical except:

void loop() {
john1.write(180);
john2.write(0);
delay(3000);
john1.write(90);
john2.write(90);
delay(1000);
john1.write(180);
john2.write(180);
delay(1000);
john1.write(90);
john2.write(90);
delay(1000);
john1.write(0);
john2.write(0);
delay(1000);

Worked on this more today. Turns out that there was some issue with powering the servos and arduino from a single 9 V. The board wasn't running the prior sketch, but was resetting after the delay function (figured this out by playing with the times and noticing that the "L" led was blinking when running from the battery). Powering the servos from a separate AAA battery pack resolved the issue.

Thanks for taking the time to post an update csuhr! I'm glad to hear you found the solution.

Yup, that would do it.

Those rectangular 9v "smoke detector" batteries are not fit for powering a project.

Also, what voltage are the servos meant to run from? Please tell me you are not powering them from the 5v rail of the Arduino; it can't take that current, especially if the regulator has to drop 4v. Use a stack of AA batteries - maybe 6? and put the battery power onto a cheap buck converter (like the kind you can get for a buck and change on ebay, search dc-dc step-down, buy some spares, because the super cheap ones fail dramatically if you short the output) to get the operating voltage of the servos, and you should be able to power the arduino from the batteries through barrel jack.