// I am trying to get the top servo to light the top led when vertical and the green when 45 deg to right.
// Then the same for the lower servo but lighting the lower leds this time.
// This is for my grandchilds train set. I have the servos working right but can't figure the leds.
#include <Servo.h>
const byte ButtonCount = 2;
// constants won't change
const int BUTTON_PINS[ButtonCount] = {7, 8, }; // Arduino pin connected to button's pin
const int SERVO_PINS[ButtonCount] = {9, 10, }; // Arduino pin connected to servo motor's pin
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
Servo servos[ButtonCount]; // create servo object to control a servo
// variables will change:
int angles[ButtonCount] = {0, 0,}; // the current angle of servo motor in this case one motor is setup at 45 deg. the other 0 deg.
int lastButtonStates[ButtonCount] = {HIGH, HIGH,}; // the previous state of button
void setup()
{
Serial.begin(9600); // initialize serial
for (int i = 0; i < ButtonCount; i++)
{
pinMode(BUTTON_PINS[i], INPUT_PULLUP); // set arduino pin to input pull-up mode
servos[i].attach(SERVO_PINS[i]); // attaches the servo on pin 9 to the servo object
servos[i].write(angles[i]);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
}
}
void loop()
{
for (int i = 0; i < ButtonCount; i++)
{
int currentButtonState = digitalRead(BUTTON_PINS[i]); // read new state
delay (10); // added to stop push button bounce
if (lastButtonStates[i] == HIGH && currentButtonState == LOW)
{
Serial.println("The button is pressed");
// change angle of servo motor
if (angles[i] == 0)
angles[i] = 45;
else if (angles[i] == 45)
angles[i] = 0;
// control servo motor arccoding to the angle
servos[i].write(angles[i]);
}
lastButtonStates[i] = currentButtonState;
} // end of for (ButtonCount)
}