I have a project which involves a photocell, an led, a push button, and a small hobby servo (tower pro sg5010) - the project works as expected when the arduino is powered by usb, but when I switch to battery power (4 AA batteries) - it doesn't work.
When powered by batteries, the servo actually starts right up and moves to the correct angle, so I feel like it should be getting enough power, but when I push the push button, it doesn't move to the new angle. I can hear a clicking noise of the servo on a regular interval, like a clock, and my LED flickers on and off at about the same interval.
If I'm doing something wrong, can anyone point it out? If it's just that the servo is not getting enough power, is there a way to add a transistor or something so that I don't have to add a separate power supply for the servo (I'm not sure there's room in my project's enclosure).
I've attached a fritzing diagram as well as my project code.
CODE:
#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);
}