Good evening, thanks for taking the time to have a look at my issue! I've put together what I think is a simple program to control two micro servos which control two cat ears for a toy project. I'm using a 5v arduino pro mini, a button attached to pin 2 with a 5k pull-down resistor.
I'm powering it with a 9v battery. These servos are tiny but I seem to be having trouble with them. I'm pretty sure the board and power supply has enough juice to get what i want because i tried this test program:
http://www.robotoid.com/appnotes/arduino-operating-two-servos.html and they move ok, it's just when i try and bring a button into the mix that i have problems.
What I'd like to happen is the following:
Button is pressed
light comes on
Power is given to servos
one servo rotates clockwise(to 180), the other anti-clockwise( to 0)
They stay there for a moment
They are both returned to 90 (central position)
power is removed.
light goes off
What actually happens is when I press the button the light comes on, one servo moves around, then they go off. The second time I press the button the light comes on but doesn't turn off, it just hangs with the servos powered (buzzing).
I'm trying to work out if it's my code or something to do with the servos i'm using.
Many thanks - see the code below.
/*
Cat ears
Turns on and off two servos connected to digital button
*/
#include <Servo.h>
Servo servoLeft; // Define left servo
Servo servoRight; // Define right servo
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
servoLeft.attach(10); // Set left servo to digital pin 10
servoRight.attach(9); // Set right servo to digital pin 9
earsback(); // put ears back
delay(2000); // Wait 2000 milliseconds (2 seconds)
reset(); //put ears forwards
delay(2000); //delay to let it get there
servoLeft.detach(); //detach servo
servoRight.detach(); //detach servo
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
// Motion routines for putting ears back and reset
void earsback() {
servoLeft.write(0);
servoRight.write(180);
}
void reset() {
servoLeft.write(90);
servoRight.write(90);
}