I am trying to make a program that makes a servo turn one direction when one button is pressed, and another direction when another is pressed, and return to the start position when no buttons are pressed. Just one button works fine, but when I try to use two, the servo spazzes out. What is the problem? Thanks in advance.
#include <Servo.h>
int button1 = 12; //button pin, connect to ground to move servo
int press1 = 0;
int press2 = 0;
int button2 = 11;
Servo servo1;
void setup()
{
pinMode(button1, INPUT_PULLUP);
servo1.attach(13);
digitalWrite(13, HIGH); //enable pullups to make pin high
}
Have you sat down and traced what that code should be doing? Because that's what you see it do.
Those code lines take microseconds if that each to run. That loop() cycles 1000's of times in less time than you can possibly notice.
When you give the servo a command to point one way and another command to point some other way less than a millisecond later, the servo will stop the first immediately to obey the second.
Your project is doing what you coded, read your code with what you see in mind.
Hint: Don't go by button states. Go by button state changes.
BTW, see if your current code makes your servo get hot.
#include <Servo.h>
// byte is an 8 bit unsigned integer that can count from 0 to 255.
// int is a 16 bit signed integer that can count from -32768 to 32767.
// int takes twice the RAM for what you don't need to track pin numbers
// automatically making variables int is a bad habit for a microcontroller programmer
byte button1 = 12; //button pin, connect to ground to move servo
byte press1 = 0;
byte last1 = 0;
byte press2 = 0;
byte last2 = 0;
byte button2 = 11;
Servo servo1;
void setup()
{
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
servo1.attach(13);
digitalWrite(13, HIGH); //enable pullups to make pin high
}
void loop()
{
press1 = digitalRead(button1);
press2 = digitalRead(button2);
if ( press1 != last1 ) // only looking for button state change, once is enough
{
last1 = press1;
if (press1 == LOW)
{
servo1.write(180);
}
else
{
servo1.write(0);
}
}
if ( press2 != last2 ) // only looking for button state change, once is enough
{
last2 = press2;
if (press2 == LOW)
{
servo1.write(0); // because 360 degrees == 0 degrees
}
else
{
servo1.write(90);
}
}
}
[/quote]
How about you figure out how/why that code works and why your other code does not?
Don't just bump over the first clue and say aha, know the whole thing so you can apply pieces or the whole to other code you try in future.