Go Down

Topic: Multiple Servo Control (Read 1 time) previous topic - next topic

ebun91

I'm doing a project where I have to control multiple servos with one arduino. I have this code I used for one servo, but I don't know if it will work for more than one. What do I have to do? Can I just do the code over again and define more buttons? Here is the code. Thanks.
Code: [Select]

#include <Servo.h>
Servo myservo; 
int pos = 0;   

const int buttonPinleft = 2;
const int buttonPinright = 5;

int buttonStateleft = 0;
int buttonStateright = 0;

void setup()
{

  pinMode(buttonPinleft, INPUT);
  pinMode(buttonPinright, INPUT);     
  myservo.attach(9);
}


void loop()
{

  buttonStateleft = digitalRead(buttonPinleft);
  buttonStateright = digitalRead(buttonPinright);

  if (pos<180) pos=180;
  if (pos>0) pos=0;

  if (buttonStateleft == HIGH) {
    pos += 5;
  }
  if (buttonStateright == HIGH) {
    pos -= 5;
  }
 
    myservo.write(pos);
    delay(0);
}

johnwasser


I'm doing a project where I have to control multiple servos with one arduino. I have this code I used for one servo, but I don't know if it will work for more than one. What do I have to do? Can I just do the code over again and define more buttons?


Create as many Servo objects as you need (up to the Arduino UNO limit of 12 or Arduino Mega limit of 48). Use the .attach() method to associate each Servo object with an output pin.

You can have as many buttons as you have spare digital pins.  If you run out of pins there are hardware ways to connect more buttons than pins.
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

ebun91


ebun91

How do I connect more buttons than pins? I just realized that I will need a lot more pins than available. What do I have to do?

johnwasser

There are several choices.  The cheapest is probably the R/2R resistor ladder that changes your button pushes to voltages on an analog input.  Using that method, each of the 6 analog inputs can read at least four buttons (24 buttons total).

http://blog.littlebirdelectronics.com/tutorial-analog-input-for-multiple-buttons-pa
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Go Up