I am using servo motors with an arduino nano clone to operate two turnouts. I cannot get the servos to work. They go to an initial position, but the buttons will not operate the servos as they should. Each switch has two LEDs one of which should be lit for position indication. One of the LEDs stays lit and the other goes on when one button is pressed and off when the other is pressed. The buttons are on analog inputs used as digital. I have 10K resistors on these input pins to prevent spurious HIGH signals. I have not yet determined exactly what servo positions are needed, just trying to get it working. Is there a problem with my code, or do I have a hardware/wiring problem? Code is below - Thanks!
#include <Servo.h>
// constant variables used to set servo angles, in degrees
const int straight1 = 90;
const int divergent1 = 110;
const int straight2 = 90;
const int divergent2 = 110;
// constant variables holding the ids of the pins we are using
const int divergent_led1 = 6;
const int straight_led1 = 7;
const int buttonpin1 = A1;
const int buttonpin1a = A3;
const int servopin1 = 8;
const int divergent_led2 = 9;
const int straight_led2 = 10;
const int buttonpin2 = A2;
const int buttonpin2a = A4;
const int servopin2 = 11;
// create a servo object
Servo Myservo1;
Servo Myservo2;
void setup()
{
// set the mode for the digital pins in use
pinMode(buttonpin1, INPUT);
pinMode(buttonpin1a, INPUT);
pinMode(straight_led1, OUTPUT);
pinMode(divergent_led1, OUTPUT);
pinMode(buttonpin2, INPUT);
pinMode(buttonpin2a, INPUT);
pinMode(straight_led2, OUTPUT);
pinMode(divergent_led2, OUTPUT);
// setup the servo
Myservo1.attach(servopin1); // attach to the servo on pin 8
Myservo2.attach(servopin2); // attach to the servo on pin 11
Myservo1.write(divergent1); // set the initial servo position
Myservo2.write(divergent2); // set the initial servo position
// set initial led states
digitalWrite(straight_led1, LOW);
digitalWrite(divergent_led1, HIGH);
digitalWrite(straight_led2, LOW);
digitalWrite(divergent_led2, HIGH);
}
void loop()
{
if (digitalRead(buttonpin1) == HIGH){
digitalWrite(straight_led1, LOW);
digitalWrite(divergent_led1, HIGH);
Myservo1.write(divergent1);
}
if(digitalRead(buttonpin1a) == HIGH){
digitalWrite(straight_led1, HIGH);
digitalWrite(divergent_led1, LOW);
Myservo1.write(straight1);
}
if(digitalRead(buttonpin2) == HIGH){
digitalWrite(straight_led2, LOW);
digitalWrite(divergent_led2, HIGH);
Myservo2.write(divergent2);
}
if(digitalRead(buttonpin2a) == HIGH){
digitalWrite(straight_led2, HIGH);
digitalWrite(divergent_led2, LOW);
Myservo2.write(straight2);
}
}// end of loop