One step at a time
Hi all, I need to increase from 1 servo to 2 with LEDs.
Please see attachment
Can some help me by altering my code to operate 2 Servos & LEDs (from that hopefully I can learn to take my project further) , Many thanks Terry.
Code for servo control by Push Button with LEDs
#include <Servo.h>
const int straight = 90;
const int divergent = 110; // constant variables used to set servo angles, in degrees
const int divergent_led = 6;
const int straight_led = 7;
const int buttonpin = 8;
const int servopin = 9; // constant variables holding the ids of the pins we are using
const int step_delay = 70; // servo movement step delay, in milliseconds
Servo myservo; // create a servo object
int pos = straight; // current
int old_pos = pos; // previous// global variables to store servo position
void setup()
{
pinMode(buttonpin, INPUT);
pinMode(straight_led, OUTPUT);
pinMode(divergent_led, OUTPUT); // set the mode for the digital pins in use
myservo.attach(servopin); // attach to the servo on pin 9
myservo.write(pos); // set the initial servo position // setup the servo
digitalWrite(straight_led, HIGH);
digitalWrite(divergent_led, LOW); // set initial led states
}
void loop()
{
int button_state = digitalRead(buttonpin); // start each iteration of the loop by reading the button
if(button_state == HIGH){ // if the button is pressed (reads HIGH), move the servo
if(pos == straight){
digitalWrite(straight_led, LOW);
} else {
digitalWrite(divergent_led, LOW); // turn off the lit led
}
old_pos = pos; // save the current position
pos = pos == straight ? divergent: straight; // Toggle the position to the opposite value
// Move the servo to its new position
if(old_pos < pos){ // if the new angle is higher
// increment the servo position from oldpos to pos
for(int i = old_pos + 1; i <= pos; i++){
myservo.write(i); // write the next position to the servo
delay(step_delay); // wait
}
} else { // otherwise the new angle is equal or lower
// decrement the servo position from oldpos to pos
for(int i = old_pos - 1; i >= pos; i--){
myservo.write(i); // write the next position to the servo
delay(step_delay); // wait
}
}
if(pos == straight){
digitalWrite(straight_led, HIGH);
} else {
digitalWrite(divergent_led, HIGH); // turn on the appropriate LED.
}
}
} // end of loop