Go Down

Topic: trying to add a second servo (Read 1 time) previous topic - next topic

andywolfman

ok here is what i'm doing. i've made a coding to control one servo to sweep from position 90, being 90 degrees to go to position 174 and back on a single push button. what i'm trying to do is add another servo on a different pin and controlled by the same button, i'm thinking pin 6 and i want that servo to sweep from 90 degrees to 6 degrees, the opposite direction and i've figured out and additional power-source for the additional servo. here is the code for the one servo. any help will be appreciated. thank you.

#include <Servo.h>

int inputPin = 10;      // Push button input pin
int btnVal = 0;         // Current value of pushbutton
int ledPin = 13;         // Pin for white LED
int outputPin = 9;      // Servo pin
int servo_pos = 0;      // Current servo position
int servo_pos_a = 90;   // Position destination a
int servo_pos_b = 174;   // Position destination b
int servo_state = 0;    // 0 = position a, 1 = position b

Servo mrservo;  // create servo object to control the servo

void setup() {
pinMode(inputPin, INPUT); // Push Button
pinMode(ledPin, OUTPUT); // LED
mrservo.attach(outputPin);  // attaches the servo on pin 9 to the servo object
Serial.begin(9600);
Serial.println("Starting...");
}

void loop() {
btnVal = digitalRead(inputPin);
if(btnVal == LOW) {
Serial.println("Button: LOW");
if(servo_state) {
Serial.println("Position: a");

} else {
Serial.println("Position: b");
}
}
if(btnVal == HIGH) {
Serial.println("Button: HIGH");
if(servo_state) {
Serial.println("Position: a");
} else {
Serial.println("Position: b");
}
// Move from position a to position b
if(servo_state == 0) {
Serial.print(servo_pos_a); Serial.print(" to "); Serial.println(servo_pos_b);
for(servo_pos = servo_pos_a; servo_pos < servo_pos_b; servo_pos += 3) {
mrservo.write(servo_pos);
digitalWrite(ledPin, HIGH);
delay(15);                       // waits 15ms for the servo to reach the position
}
servo_state = 1;
} else {  // Move from position b to position a
Serial.print(servo_pos_b); Serial.print(" to "); Serial.println(servo_pos_a);
for(servo_pos = servo_pos_b; servo_pos >= servo_pos_a ; servo_pos -= 3) {
mrservo.write(servo_pos);
digitalWrite(ledPin, LOW);
delay(15);
}
servo_state = 0;
}
}
// Separate each cycle's output
Serial.println(); Serial.println();
delay(250);
}

fliggygeek

So, you will need to declare another servo, for example :

Code: [Select]
Servo secondServo;

Declare its pin:

Code: [Select]
secondServo.attach(6);

Then, you need to make a second set of for statements to form a value for the second servo.
Looking at your code, are you aware that if u send the servo a value of 90 then directly send 174, it will move the distance between those values itself without needing any intermediate values? Or is there a reason for your coding?


Go Up