Hey, I tried to make a code where pressing a button makes a servo go right, and pressing another button makes it go left. The servo just spins left, right, waits a second, and loops. Any help?
#include <Servo.h>
int left = LOW;
int right = LOW;
int pos = 0;
Servo first;
void setup()
{
first.attach(9);
pinMode(11, INPUT);
pinMode(12, INPUT);
}
void loop()
{
left = digitalRead(11);
right = digitalRead(12);
if (left = HIGH)
{
while (left == HIGH)
{
left == digitalRead(11);
pos++;
first.write(pos);
}
}
if (right = HIGH)
{
while (right == HIGH)
{
right == digitalRead(12);
pos--;
first.write(pos);
}
}
}
Make sure you have an external power supply for the servo, and the external power supply ground is connected to the arduino ground. Below is some button type test code.
//zoomkat servo button test 12-29-2011
#include <Servo.h>
int button1 = 4; //button pin, connect to ground to move servo
int press1 = 0;
int button2 = 5; //button pin, connect to ground to move servo
int press2 = 0;
Servo servo1;
void setup()
{
pinMode(button1, INPUT);
pinMode(button2, INPUT);
servo1.attach(7);
digitalWrite(4, HIGH); //enable pullups to make pin high
digitalWrite(5, HIGH); //enable pullups to make pin high
}
void loop()
{
press1 = digitalRead(button1);
if (press1 == LOW)
{
servo1.write(170);
}
press2 = digitalRead(button2);
if (press2 == LOW)
{
servo1.write(10);
}
/*else {
servo1.write(90);
}*/
}