Battery vs USBB power differences

When connected to USB power the project works as expected - the sensor triggers (or passive buzzer sounds) when the object is in range. However, when connected to battery, the sensor stays on and emits constant vibration, as does the passive buzzer emitting constant sound.

The sketch is as follows:

// Define pins for ultrasonic and buzzer
int const trigPin = 13;
int const echoPin = 11;
int const buzzPin = 6;

void setup()
{
pinMode(trigPin, OUTPUT); // trig pin will have pulses output
pinMode(echoPin, INPUT); // echo pin should be input to get pulse width
pinMode(buzzPin, OUTPUT); // buzz pin is output to control buzzering
}

void loop()
{
// Duration will be the input pulse width and distance will be the distance to the obstacle in centimeters
int duration, distance;
// Output pulse with 1ms width on trigPin
digitalWrite(trigPin, HIGH);
delay(1);
digitalWrite(trigPin, LOW);
// Measure the pulse input in echo pin
duration = pulseIn(echoPin, HIGH);
// Distance is half the duration devided by 29.1 (from datasheet)
distance = (duration/2) / 29.1;
// if distance less than 0.5 meter and more than 0 (0 or less means over range)
// if (distance <= 50 && distance >= 0) {

// if distance less than 3.0 meter and more than 0 (0 or less means over range)
if (distance <= 300 && distance >= 0) {
// Buzz
digitalWrite(buzzPin, HIGH);
} else {
// Don’t buzz
digitalWrite(buzzPin, LOW);
}
// Waiting 60 ms won’t hurt any one
delay(60);
}

Thanks in advance!

What kind of battery are you using? Do you have a multimeter to measure the voltage to make sure the voltage is "holding-up"?

There should be no difference between USB and battery for your sketch. Your problem most likely lies in the circuit design. This is where we can't help you without knowing the board, batteries, schematic and parts you are using. I would take a look at your wiring and see if everything is correctly wired and that you have nicely charged batteries with enough voltage to run everything.

HELP NEEDED... School Project

We are down to the last piece, everything is coded and working but we cannot get the motor to stop responding when on battery power.On USB it works and only triggers when detecting an object. On battery, it trips constantly. Any one else encounter this before?

Thanks!

gcifatte: Any one else encounter this before?

Yes, not many, but you can always tell who they are. They are the sort of people who refuse to read or answer replies #1 and #2.