I am having some difficulties in trying to make my servo motor move to a specific angle based on the button pressed.
For example, having the motor start at 0 degrees and then having it move to 180 when the 3rd button is pressed, have it return to 0 degrees when the first button is pressed, and have it go to 90 degrees when the second button is pressed, etc, etc.
I can't tell if I am going about this all wrong or not with my code, so if anyone could provide some assistance with this it would be a great help
EDIT: Added the wiring as a just in case
#include <Servo.h>
Servo myservo;
int angle = 0;
int anglestep = 10;
#define FIRST 2 // pin 2 is connected to 1st floor button
#define SECOND 3 // pin 3 is connected to 2nd floor button
#define THIRD 4 // pin 4 is connected to 3rd floor button
#define SIGNAL 10
void setup()
{
Serial.begin(9600);
myservo.attach(10);
myservo.write(angle);
pinMode(2,INPUT_PULLUP);
pinMode(3,INPUT_PULLUP);
pinMode(4,INPUT_PULLUP);
Serial.println("Lift/Descend");
}
void loop()
{
while (digitalRead(FIRST) == LOW)
{
if (angle > 0 && angle <= 90) //2to1
{
angle = angle - anglestep;
if (angle < 0)
{
angle = 0;
}
else
{
myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle);
Serial.println(" degree");
}
}
else if (angle > 90 && angle <= 180) //3to1
{
angle = angle - anglestep;
if (angle < 0)
{
angle = 0;
}
else
{
myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle);
Serial.println(" degree");
}
}
else //1on1
{
angle = 0;
}
}
while (digitalRead(SECOND) == LOW)
{
if (angle > 90 && angle <= 180) //3to2
{
angle = angle - anglestep;
if (angle > 90)
{
angle = 90;
}
else
{
myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle);
Serial.println(" degree");
}
}
else if (angle > 0 && angle < 90) //1to2
{
angle = angle + anglestep;
if (angle < 90)
{
angle = 90;
}
else
{
myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle);
Serial.println(" degree");
}
}
else
{//2on2//
angle = 90;
}
}
while (digitalRead(THIRD) == LOW)
{
if (angle > 0 && angle <= 90) //1to3
{
angle = angle + anglestep;
if (angle > 180)
{
angle = 180;
}
else
{
myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle);
Serial.println(" degree");
}
}
else if (angle > 90 && angle < 180)
{//2to3
angle = angle + anglestep;
if (angle > 180)
{
angle = 180;
}
else
{
myservo.write(angle);
Serial.print("Moved to: ");
Serial.print(angle);
Serial.println(" degree");
}
}
else
{
angle = 180;
}
}
}