Go Down

Topic: Control Servos with Potentiometers (Read 589 times) previous topic - next topic

dp22

Hello,
I have used the code below to control a servo using a potentiometer. I need to now do the same but with multiple servos and potentiometers. I am using the ANALOG 0 and DIGITAL 9 PINS on the Arduino. I am very new to this and need help knowing what I need to and don't need to duplicate in the program. I need to do a total of 3 servos.

Thanks a lot!!
p.s. does anyone know how to power three servos separately from the arduino with a adapter they are rated 6v each. Let me know.



#include <Servo.h>

Servo arm;  // create servo object to control a servo

int armpin = 0;  // analog pin used to connect the potentiometer
int armval;    // variable to read the value from the analog pin

void setup()
{
  arm.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  armval = analogRead(armpin);            // reads the value of the potentiometer (value between 0 and 1023)
  armval = map(armval, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180)
  arm.write(armval);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}

MarkT

An array of pin numbers for the inputs and another one for the outputs would be a sensible approach:
Code: [Select]

#include <Servo.h>

Servo arm[3] ;  // create servo object to control a servo

int arm_pins [] = { A0, A1, A2 } ;  // analog pins used to connect the potentiometers
int servo_pins [] = { 9,  10, 11 } ;

void setup()
{
 for (int i = 0 ; i < 3 ; i++)
   arm[i].attach(servo_pins [i]);  // attaches the servos to their pins
}

void loop()
{
  for (int i = 0 ; i < 3 ; i++)
    arm[i].write (map (analogRead (arm_pins [i]), 0, 1023, 0, 179)) ;
 delay(15);                           // waits for the servos to get there
}


(untested, but you get the idea)
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy