# Multiple servos with buttons

**URL:** <https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738>\
**Category:** Programming\
**Created:** [November 19, 2022, 11:02pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738 "2022-11-19T23:02:17Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![ester\_k](https://avatars.discourse-cdn.com/v4/letter/e/85e7bf/32.png) [@ester\_k](https://forum.arduino.cc/u/ester_k)\
**Post date:** [November 19, 2022, 11:02pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/1 "2022-11-19T23:02:17Z")

</div>

Hi, so, I am new with Arduino and I have problem with this code. I need the first servo to move when the first button is clicked. After clicking the second button, the second servo should move.  
The first servo is moving. As it should. But the second servo does not respond to the button. There is probably a small error in the code, maybe I separated the sections wrong?  
I am giving you a link to the simulation with the code. I hope someone will be able to help me. Probably only a small code modification is needed, but I don't know what exactly. Thanks for the anwers.  
[Here is link](https://www.tinkercad.com/things/hVNlUaHnk8E-multiple-buttons-and-servos), just start a simulation and click at buttons. You can view the code in the link or below:

```cpp
#include <Servo.h>

// constant variables used to set servo angles, in degrees
const int straight = 90; 
const int divergent = 110;

// constant variables holding the ids of the pins we are using
const int buttonpinA = 8;
const int servopinA = 9;
const int buttonpinB = 6;
const int servopinB = 7;

// servo movement step delay, in milliseconds
const int step_delay = 70;

// create a servo object
Servo myservoA;
Servo myservoB;
 
// global variables to store servo position
int pos = straight; // current
int old_pos = pos; // previous

void setup() 
{ 
  // set the mode for the digital pins in use
  pinMode(buttonpinA, INPUT);
  pinMode(buttonpinB, INPUT);
   
  // setup the servo
  myservoA.attach(servopinA); // attach to the servo on pin 9
  myservoA.write(pos); // set the initial servo position
  myservoB.attach(servopinB); // attach to the servo on pin 7
  myservoB.write(pos); // set the initial servo position
}

void loop() 
{ 
  int button_state = digitalRead(buttonpinA);
  if(button_state == HIGH){
    
    old_pos = pos;   
    
    pos = pos == straight ? divergent: straight;
       
    
    if(old_pos < pos){   
      
      for(int i = old_pos + 1; i <= pos; i++){  
        myservoA.write(i); 
        delay(step_delay); 
      }
    } else {  
      
      for(int i = old_pos - 1; i >= pos; i--){ 
        myservoA.write(i); 
        delay(step_delay); 
      }
    } 

   int button_state = digitalRead(buttonpinB);
   if(button_state == HIGH){
    
    old_pos = pos;   
    
    
    pos = pos == straight ? divergent: straight;
       
    
    if(old_pos < pos){   
      
      for(int i = old_pos + 1; i <= pos; i++){  
        myservoB.write(i); 
        delay(step_delay); 
      }
    } else {  
      
      for(int i = old_pos - 1; i >= pos; i--){ 
        myservoB.write(i); 
        delay(step_delay); 
      }
    }
    
  } 
}}// end of loop

```

![servo](https://europe1.discourse-cdn.com/arduino/original/4X/7/d/3/7d3512169d674a672c5168cdf6c8ec0a7d10f57e.jpeg)

---

<div class="post-metadata">

**Author:** ![touch1337](https://avatars.discourse-cdn.com/v4/letter/t/bb73d2/32.png) [@touch1337](https://forum.arduino.cc/u/touch1337)\
**Post date:** [November 19, 2022, 11:32pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/2 "2022-11-19T23:32:04Z")

</div>

Try making different variable names for each section of the code rather than reusing them.  
button\_state changes to button\_a\_state and button\_b\_state, old\_pos becomes old\_pos\_servo1 and old\_pos\_servo2, etc.

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [November 20, 2022, 12:33am UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/3 "2022-11-20T00:33:44Z")

</div>

Hi Ester,

welcome to the forum.  
Running your simulation requires registering at autodesk.  
I will definitely **not** register at autodesk.  
autodesk is a company that has a very aggressive marketing strategy to pour into every edge of schools and DIY-projects by offering "get used to our products for free"

There is another simulator that is opensource.  
It is called wokwi

here is the WOKWI simulation of your code with a own set of variables for servo A and another set of variables for servo B

Though I guess this is still not that what you want.

I try to write down a precise description of what you probably want

As long as button A is pressed move servo A. If button A is released servo A shall stop at what ever position it is.

at the same time = in parallel  
As long as button B is pressed move servo B. If button B is released servo B shall stop at what ever position it is.

This is medium advanced programming by using non-blocking timing

Non blocking timing means  
there is only one big loop which is void loop() **itself**  
There are zero function-calls to delay() and there are zero for-loops and zero while-loops  
because all three

- delay()
- for-loops
- while-loops

are blocking.  
Which means as long as the delay / for / while is executing nothing else can happen.

They way to go there is structured programming

build your own functions

as pseude-code

```arduino
void moveServoA()
// all the code that makes the servo move back and forth slowly 
// but with non-blocking timing

void moveServoB()
// all the code that makes the servo move back and forth slowly 
// but with non-blocking timing

if (buttonA is pressed) {
  moveServoA()
}

if (buttonB is pressed) {
  moveServoB()
}

```

To understand non-blocking timing requires a prelimary exercise to understand it  
the basic principle is to store snapshots of time and check how much time has passed by since storing the snapshot of time

> [@Example-code for timing based on millis() easier to understand through the use of example-numbers / avoiding delay()](https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017):
>
> non-blocking timing. Execute code only from time to time. There are a lot of different ways to learn programming. This thread wants to add another approach that is different to the yet existing ones. UPDATE 06.01.2023 if you are mainly interested in applying non-blocking timing you can do a quick read of this short tutorial / demonstration If you are intersted in understanding the details how it works go on reading here. I use an everyday analogon in this post to explain the basic principle …

best regards Stefan

---

<div class="post-metadata">

**Author:** ![ester\_k](https://avatars.discourse-cdn.com/v4/letter/e/85e7bf/32.png) [@ester\_k](https://forum.arduino.cc/u/ester_k)\
**Post date:** [November 20, 2022, 10:10am UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/4 "2022-11-20T10:10:23Z")

</div>

Hi, thank you for telling me about Wokwi. As I said, I am pretty new in this community.  
My explanation of the problem was poorly written. Sorry about that. Here is a more understandable version:  
In Wokwi, I made a diagram for moving one servo using a button. When you press the button, the servo will move a little. When you press the button again, the servo will return to the previous position. When you run the simulation, the code does exactly what I need ([here is link](https://wokwi.com/projects/348839408048276052)).  
All I need is how to do the code if I need to have multiple servos with their own button powered by one Arduino.  
For example: If I press button A, servo A will move. If I press button B, servo B will move regardless of what position servo A is in.  
I want to use a breadboard for power and grounding (as on picture).  
 ![servo](https://europe1.discourse-cdn.com/arduino/original/4X/7/d/3/7d3512169d674a672c5168cdf6c8ec0a7d10f57e.jpeg)

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [November 20, 2022, 10:19am UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/5 "2022-11-20T10:19:06Z")

</div>

> [@ester\_k](#):
>
> But the second servo does not respond to the button.

the more properly formatted (indented) code shows that the 2nd button is read within the condition for the 1st button

```arduino
void loop()
{
    int button_state = digitalRead(buttonpinA);
    if(button_state == HIGH){
        old_pos = pos;
        pos = pos == straight ? divergent: straight;
        if(old_pos < pos){
            for(int i = old_pos + 1; i <= pos; i++){
                myservoA.write(i);
                delay(step_delay);
            }
        } else {
            for(int i = old_pos - 1; i >= pos; i--){
                myservoA.write(i);
                delay(step_delay);
            }
        }
        int button_state = digitalRead(buttonpinB);
        if(button_state == HIGH){
            old_pos = pos;
            pos = pos == straight ? divergent: straight;
            if(old_pos < pos){
                for(int i = old_pos + 1; i <= pos; i++){
                    myservoB.write(i);
                    delay(step_delay);
                }
            } else {
                for(int i = old_pos - 1; i >= pos; i--){
                    myservoB.write(i);
                    delay(step_delay);
                }
            }
        }
    }
}// end of loop

```

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [November 20, 2022, 10:47am UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/6 "2022-11-20T10:47:46Z")

</div>

For the independant operation of both servos the whole code must follow the non-blocking paradigma.

Non-blocking means:  
the most outer loop which is

```arduino
void loop() {
//top of loop
// any kind of code (can be THOUSANDs of lines of code)
// bottom of loop
}

```

must run down **completely** at high speed from  
//top of loop  
down to  
// bottom of loop

to make sure that this is running down fast  
all lines of code inbetween must be finished fast

This can be achieved by a coding-structure that makes sure to  
quickly jump into a sub-function and quickly jump out again

```arduino
void loop() {
  myFunctionOne(); // quickly jump in / quickly jump out 
  myFunctionTwo(); // quickly jump in / quickly jump out 
  //....
  myFunction10(); // quickly jump in quickly jump out 
}

```

Not all code shall be executed at all times.  
This means code-execution is made **conditional**

```arduino
void myFunctionOne() {
  if (ExecutionConditionONE == true) {
    // execute code
  }
  else {
    //doNothing
  }
  
}

void myFunctionTwo() {
  if (ExecutionConditionTwo == true) {
    // execute code
  }
  else {
    //doNothing
  }
  
}

```

for-loops and while-loops must be avoided **completely**

counting variables up/down is done bye each new call of the sub-functions

```arduino
void myFunctionOne() {
  if (ExecutionConditionONE == true) {
    posA = posA + 1; 
  }
  else {
    //doNothing
  }
  
}

```

remember: loop() is looping at high speed **all** the time  
This means the sub-function is called over an over again through **void loop()**  
instead of a for-loop

Now changing the servo-position slowly requires non-blocking timing  
which is explained here

> [@Example-code for timing based on millis() easier to understand through the use of example-numbers / avoiding delay()](https://forum.arduino.cc/t/example-code-for-timing-based-on-millis-easier-to-understand-through-the-use-of-example-numbers-avoiding-delay/974017):
>
> non-blocking timing. Execute code only from time to time. There are a lot of different ways to learn programming. This thread wants to add another approach that is different to the yet existing ones. UPDATE 06.01.2023 if you are mainly interested in applying non-blocking timing you can do a quick read of this short tutorial / demonstration If you are intersted in understanding the details how it works go on reading here. I use an everyday analogon in this post to explain the basic principle …

---

<div class="post-metadata">

**Author:** ![ester\_k](https://avatars.discourse-cdn.com/v4/letter/e/85e7bf/32.png) [@ester\_k](https://forum.arduino.cc/u/ester_k)\
**Post date:** [November 20, 2022, 12:55pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/7 "2022-11-20T12:55:59Z")

</div>

When I added your code (I hope I have permission?) I got this error message. I don't know Arduino well, so I don't know exactly what that means. I am giving a link to the simulation [here](https://wokwi.com/projects/348849806726136404).

 ![servo2](https://europe1.discourse-cdn.com/arduino/original/4X/d/4/7/d47ccf895a0ee7026fd57748aa7992ad59dac7e8.jpeg)

---

<div class="post-metadata">

**Author:** ![ester\_k](https://avatars.discourse-cdn.com/v4/letter/e/85e7bf/32.png) [@ester\_k](https://forum.arduino.cc/u/ester_k)\
**Post date:** [November 20, 2022, 12:57pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/8 "2022-11-20T12:57:41Z")

</div>

Thanks, I will try to read everything and get better at programming.

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [November 20, 2022, 1:00pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/9 "2022-11-20T13:00:01Z")

</div>

> [@ester\_k](#):
>
> When I added your code

i simply posted a portion of your code properly formatted so that you could see that the 2nd button code was inside the condition for the first.

i had hoped you would see that this explains your problem and would know how to correct it by moving it out from inside the 1st button condition. do you need help?

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [November 20, 2022, 1:22pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/10 "2022-11-20T13:22:51Z")

</div>

Your WOKWI-simualtion has ver ynicely placed components

The error in the wowki-simulation is caused by the missing  
void setup()-function.

Take a look into this tutorial:

at least at the first 6 chapters.

[Arduino Programming Course](https://startingelectronics.org/software/arduino/learn-to-program-course/)

It is easy to understand and has a good mixture between explaining important concepts and example-codes to get you going. So give it a try and report your opinion about this tutorial.

best regards Stefan

---

<div class="post-metadata">

**Author:** ![ester\_k](https://avatars.discourse-cdn.com/v4/letter/e/85e7bf/32.png) [@ester\_k](https://forum.arduino.cc/u/ester_k)\
**Post date:** [November 20, 2022, 5:28pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/11 "2022-11-20T17:28:18Z")

</div>

All right, [there is my last try](https://wokwi.com/projects/348849806726136404). I didn't understand the code too much. So, now I will read tutorials and try to understand programming better. If someone could show me how to make my code look correct, that would be very helpful. However, thank you for your time and have a nice day.

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [November 20, 2022, 6:13pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/12 "2022-11-20T18:13:56Z")

</div>

consider

```cpp
# include <Servo.h>

const int ButtonpinA = 8;
const int ButtonpinB = 6;

const int servopinA = 9;
const int servopinB = 7;

// constant variables used to set servo angles, in degrees
const int Straight = 90;
const int Divergent = 110;

// servo movement step delay, in milliseconds
const int step_delay = 70;

// create a servo object
Servo myservoA;
Servo myservoB;

#define Nservo 2

int pos [Nservo] = { Straight, Straight };
int posOld [Nservo] = { Straight, Straight };

byte ButPins [] = { ButtonpinA, ButtonpinB };
byte butState [sizeof (ButPins)];

// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (9600);

    for (unsigned b = 0; b < sizeof(ButPins); b++) {
        pinMode (ButPins [b], INPUT_PULLUP);
        butState [b] = digitalRead (ButPins [b]);
    }

    // setup the servo
    myservoA.attach (servopinA); // attach to the servo on pin 9
    myservoA.write (pos [0]); // set the initial servo position

    myservoB.attach (servopinB); // attach to the servo on pin 7
    myservoB.write (pos [1]); // set the initial servo position
}

// -----------------------------------------------------------------------------
void loop ()
{
    int dir;
    for (unsigned b = 0; b < sizeof(ButPins); b++) {
        byte but = digitalRead (ButPins [b]);
        if (butState [b] != but) {
            butState [b] = but;

            if (LOW == but) {
                pos [b] = Straight == pos [b] ? Divergent : Straight;
                dir = (pos [b] - posOld [b]) > 0 ? 1 : -1;

                for (int i = posOld [b]; i != pos [b]; i += dir) {
                    if (0 == b)
                        myservoA.write (i);
                    else
                        myservoB.write (i);
                    delay (step_delay);
                }
                posOld [b] = pos [b];
            }
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [November 20, 2022, 6:23pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/13 "2022-11-20T18:23:17Z")

</div>

@gcjr  
have you ever **considered** for a few seconds that a code with that stage of sophistication is already wayyy above the head of a real beginner?

have you ever **considered** that presenting a to heavy to understand code **can** be frustrating?

have you ever **considered** that with this **really poor** and short comments this code

## IS

hard to understand **for a real beginner**??!!

Is your main aim to **chase away** all young people that are interested in learning coding  
except the real nerdy ones that love most to read the hardest to understand code?

If you aren't aware of that you are that forum-member that has the biggest

## experts blindness for beginner difficulties

that I have yet encountered

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [November 20, 2022, 7:22pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/14 "2022-11-20T19:22:09Z")

</div>

what do you think is so difficult?

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [November 20, 2022, 8:07pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/15 "2022-11-20T20:07:58Z")

</div>

using arrays without explaining them  
using the "?"-operator without explaining it

the compactness of code like this line

```cpp
for (unsigned b = 0; b < sizeof(ButPins); b++)

```

or this part

```cpp
if (LOW == but) {
                pos [b] = Straight == pos [b] ? Divergent : Straight;
                dir = (pos [b] - posOld [b]) > 0 ? 1 : -1;

                for (int i = posOld [b]; i != pos [b]; i += dir) {
                    if (0 == b)
                        myservoA.write (i);
                    else
                        myservoB.write (i);

```

@ester_k

your last attempt to make it work is missing the void setup-function  
and has two functions void loop()

each and every Arduino-Sketch requires to have  
exact one function

```cpp
void setup() {
}

```

and exact one function

```cpp
void loop() {
}

```

You made a good decision to learn more about the basics.

I modifyed your WOKWI-code so that it is working now.  
It works in a blocking manner  
as long as the code is executing a for-loop the code outside this for-loop is not eecuted  
of course because you are in a for-loop which runs down from start to finish

> **[sketch.ino copy - Wokwi Arduino and ESP32 Simulator](https://wokwi.com/projects/348877381879988820)**
>
> Run IoT and embedded projects in your browser: ESP32, Arduino, Pi Pico, and more. No installation required!

best regards Stefan

---

<div class="post-metadata">

**Author:** ![b707](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/b707/32/854321_2.png) [@b707](https://forum.arduino.cc/u/b707)\
**Post date:** [November 20, 2022, 8:13pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/16 "2022-11-20T20:13:38Z")

</div>

> [@StefanL38](#):
>
> using arrays without explaining them  
> using the "?"-operator without explaining it

Both are not really difficult and are easy to find in any textbook.

> [@StefanL38](#):
>
> or this part
> 
> ```arduino
> if (LOW == but) {
> pos [b] = Straight == pos [b] ? Divergent : Straight;
> dir = (pos [b] - posOld [b]) > 0 ? 1 : -1;
> 
> for (int i = posOld [b]; i != pos [b]; i += dir) {
> if (0 == b)
> myservoA.write (i);
> else
> myservoB.write (i);
> 
> ```

and this part is almost entirely taken from the own OP code!  
Do not underestimate beginners, I think OP will understand this as well as you

And in general, you should not make the task too easy for beginners, otherwise they will generally forget how to think

---

<div class="post-metadata">

**Author:** ![ester\_k](https://avatars.discourse-cdn.com/v4/letter/e/85e7bf/32.png) [@ester\_k](https://forum.arduino.cc/u/ester_k)\
**Post date:** [November 20, 2022, 10:58pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/17 "2022-11-20T22:58:52Z")

</div>

Alright guys, I have to thank you for your help. You helped me a lot, especially @StefanL38. I promise to read all the tutorials and try to get better at programming. I still have a lot to learn, but I believe I will make progress. And also thanks for making the code workable, now I can look for my mistakes.  
Have a great day and thank you again. ❤

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [May 19, 2023, 10:59pm UTC](https://forum.arduino.cc/t/multiple-servos-with-buttons/1055738/18 "2023-05-19T22:59:13Z")

</div>

Closed on May 19, 2023, 10:59pm UTC

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
