I have a project which runs a continuous loop and listens for the push of a button to light an led and activate a servo motor on an Arduino Uno (R2). The arduino is powered by 4 AA batteries, and the servo is powered by a 9V. I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this? As a side note, if anyone spots a way to improve battery life in my sketch / wiring, I'd love to know.
Below is my code and attached is the wiring diagram for the project (minus the batteries).
#include <Servo.h>
const int buttonPin = 2; // the number of the pushbutton pin
boolean buttonPushed = false;
const int ledPin = 13; // the number of the LED pin
const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;
boolean servoActivated = false;
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;
void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
servo.attach(servoPin);
servo.write(servoStartAngle);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
int photoCellVal = analogRead(photoCellPin);
if (photoCellVal > photoCellThreshold){
photoCellActivated = true;
} else {
photoCellActivated = false;
}
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == LOW && buttonPushed == false) {
// turn LED on:
buttonPushed = true;
Serial.println("button pushed");
} else if (buttonState == LOW && buttonPushed == true){
buttonPushed = false;
Serial.println('deactivate');
}
if (buttonPushed == true){
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
if (buttonPushed && servoActivated == false && photoCellActivated == true){
servoActivated = true;
Serial.println("activate motor");
for(angle = servoStartAngle; angle > servoEndAngle; angle--){
servo.write(angle);
Serial.println(angle);
delay(15);
}
} else if (buttonPushed == false && servoActivated == true){ //deactivate
for(angle = servoEndAngle; angle < servoStartAngle; angle++){
servo.write(angle);
Serial.println(angle);
delay(15);
}
delay(200);
servoActivated = false;
}
delay(200);
}