Pages: [1]   Go Down
Author Topic: Control Servos with Potentiometers  (Read 463 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 10
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
}
Logged

0
Offline Offline
Shannon Member
****
Karma: 207
Posts: 12200
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

An array of pin numbers for the inputs and another one for the outputs would be a sensible approach:
Code:
#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)
Logged

[ I won't respond to messages, use the forum please ]

Pages: [1]   Go Up
Jump to: