Servo control by push button switch arduino

In this project, the movement of the servo shaft in the clockwise and anticlockwise direction is controlled by two pushbuttons using Arduino; refer: How to use a servo with Arduino.

In the circuit, the positive supply from the +5V output is connected to one terminal side of the SPST push switch. The other terminal side is connected to the digital pin 2 and pin 3 of the Arduino board with pulldown resistors of 1KΩ (connected across the input pins and the GND terminal). So whenever the switches are pressed the digital pins get an active high state input.control servo motor with button

If the first switch is pressed the pin 2 will have an active high state, then the position of the servo starts to increments as long as the switch is held ON until it reaches a value of 180 degrees. Similarly, the servo keeps decrement to 0 degrees if the second switch is pressed.

The speed of the servo can be controlled by adjusting the time delay function; In the delay() function, the time delay is given in milliseconds. The speed of rotation is inversely proportional to the time delay value.

how to control a servo with a switchHere the servo moves only when the input is in an active high. Whenever the push button is released, the arm movement stops at the current position. And when the switch is pressed again the movement continues from the same position. If the servo is either incrementing or decrementing, the push button currently pressed has to be released in order to read the state of the other switch.

Code

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

Servo servo;
void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  servo.attach(9);
}
void loop() {
  while (digitalRead(2) == HIGH && pos < 180) {
    pos++;
    servo.write(pos);
    delay(15);
  }
  while (digitalRead(3) == HIGH && pos > 0) {
    pos--;
    servo.write(pos);
    delay(15);
  }
}

You may also like...

170 Responses

  1. Pat says:

    Hi I have a question I would like to use 1 button push it once to move the servo from 0 to 180 and keep going until I then push it again to stop it. Can this be done??
    Pat

    • admin says:

      Refer: Arduino Toggle Switch
      The code in the above project can be used to run a code block by an alternate push on a single switch. Inside it, you can add the code for 0 to 180 or 180 to 0 degree movements.

  2. Arun prabu says:

    Is it possible to control this program for three servo in the same uno board

  3. Yule says:

    I got an issue. The hole thing work but if im click the right button in he goes to right but if i click nothing the servo goes automatically trough the left.

    Can you help me

    • admin says:

      Probably it might due to loss contact or wrong connection. Make sure the pull down resistors and wires are connected properly.

  4. Yule says:

    Can you make the servo go faster. And what do i have to change in my code for that

  5. andre says:

    what is the resistors’ function in it? Is it possible to make it work without them?

    • admin says:

      It is a pull-down resistor, to hold logic low level when there is no input. It avoids a floating input and prevents an undefined input state.

  6. akuler says:

    Hi guys. really needs help. I try to make one project which can sweep the servo motor from 0 to 180 degree and back to 0 degree once triggered by one push button. Do anyone had the example of the circuit construction and the coding? Thanks in advance.

    • admin says:

      Try this code,

      if (digitalRead(Switch) == HIGH) {
        //sweep from 0 to 180 degree
        for (pos = 0; pos <= 180; pos += 1) {
          myservo.write(pos);
          delay(15);
        }
        //sweep from 180 to 0 degree
        for (pos = 180; pos >= 0; pos -= 1) {
          myservo.write(pos);
          delay(15);
        }
      }
      

      Refer Servo motor sweep code

  7. Alex says:

    is there a way to go from 90 to 180 with one button and 90 to 0 with another??? if so please respond soon

    • admin says:

      Use this code,

      while (digitalRead(2) == HIGH && pos < 180) {
        servo.write(90);
        pos++;
        servo.write(pos);
        delay(15);  
      }
      while (digitalRead(3) == HIGH && pos > 0) {
        servo.write(90);
        pos--;
        servo.write(pos);
        delay(15);
      }
      

      Here whenever you press the button the servo first comes to 90 degrees position, then only it can increments or decrements.

  8. Alex says:

    New question, which resistor is it i couldn’t make out the numbers

  9. Alex says:

    Im not going to copy you but thank you a ton this will be great as something too look off of and be useful as a advice kinda thing.

  10. Alex says:

    sorry if i’m asking too much questions but what is a pot pin, pot value and motor pin and motor value, i assume its a pin of the potentiometer and motor

    • admin says:

      Your code is to control the speed of a motor using a potentiometer. So these variables (pot pin, pot value and motor pin and motor value) are required to connect potentiometer and motor to the arduino and read and write the values respectively. Here, the pot pin is the analog pin A0 which connects to the potentiometer terminal C. And pot value is the analog value read by the input A0, which is a decimal value ranging 0 to 1023 for the corresponding input voltage range of 0-5V.
      The motor pin is the pin number which attaches the motor and motor value is the value to vary the motor speed using PWM. Here code the motor value is just the mapped value of pot value from 0-1023 to 0-255.

  11. Alex says:

    thanks that was needed alot (you are helping me alot for understanding code thank you)

  12. murali says:

    hi, admin, i need your help,
    i am using a continuous servo motor with one push button, for this if i press push button, i need 360 rotation (1 circular rotation) of the servo motor and then stop. so i need code for it as well connections also …thank you.

    • admin says:

      Unlike from Position rotation servo motors, continuous rotation servos rotates clockwise and anti-clockwise with a speed control.
      Its direction and speed are controlled by the pulse width signals between 1000us and 2000us. When the value increases from 1000us to 1500us the clockwise speed decreases and the motor stops at 1500us and on after 1500us the motor speed increases in counterclockwise direction till it reaches maximum speed at 2000us.
      1000microseconds – motor rotates clockwise at maximum speed.
      1500 microseconds – motor stops.
      2000microseconds – motor rotates counterclockwise at maximum speed.
      Set the delay value by measuring the time required to complete 1 rotation for the given speed.

      #include<Servo.h>
      int time_delay = 1000 ; // Set time delay value.
      
      Servo servo;
      void setup() {
         pinMode(2, INPUT);
         servo.attach(9);
      }
      void loop() {
         if (digitalRead(2) == HIGH) {
          servo.writeMicroseconds(1000); // rotates clockwise at full speed
          delay(time_delay);
          servo.writeMicroseconds(1500); // rotation stops  
        }
      }
      

      Just ignore the arrangement for Input at pin3, except the connection is same as in the post.

      • murali says:

        thank you, but
        the problem with speed ,the motor is rotating continuously not stoping and initially with out pressing push button the motor is rotating continuously , but i need when we prees the push button that time should start the servo motor and 2 rotations of the motor shaft and then stop the motor automatically….thank you i am waiting for the code…

        • murali says:

          AND one more situation if pushbutton press continuously the motor is also rotating continuously for this i need some delay after pressing the push button.

        • admin says:

          The problem may be related to the connection, make sure the input has a proper connection with a pull-down resistor.

  13. nate says:

    hi how would i write a default position in to the code so that when a button is released the servo goes back to a set degree like 90.

  14. nate says:

    hi can you use this code to control multiple servos at once.

  15. Murali says:

    Ultrasonic sensor with continuous servomotor for Arduino I need code with connections where to give but I need 2sec motor rotate and then stop

    • admin says:

      Refer : Ultrasonic sensor with servo motor.
      For 2 second rotation use this code,

      servo.writeMicroseconds(1000); //clockwise at full speed
      delay(2000);
      servo.writeMicroseconds(1500); //stop
      
      • murali says:

        sir, i need full code i am new to Arduino please.

        • admin says:

          For an ultrasonic scanner with servo, what type of motion you need? Does it should rotate with a code only or controlled by a push button.

          • murali says:

            i am not using push button, i am using the ultrasonic sensor with the continuous servo motor in Arduino, i need only one direction rotation with some (time 2 or 3 seconds) time and then stop .please sir i need code and connections. here input is the ultrasonic sensor.

          • admin says:

            For connection and ultrasonic sensor mounting, refer the link of “object scanner with Ultrasonic Servo rover“.
            Try this,
            Replace the code inside the void loop of Ultrasonic servo rover with the below code.

            for (int i = 0; i <= 100; i++) {
              // rotates clockwise at full speed
              servo.writeMicroseconds(1000);
              delay(20);
              // rotation stops
              servo.writeMicroseconds(1500);
              // Serial print Ultrasonic sensor value
              Serial.println(radar());
            }
            
  16. nate says:

    hi i’m hoping you can help again, I’ve modified a bit of code so that a continuous servo can rotate and the return but, i’m struggling to be able to flip it so it does the opposite ( ie wanting to control a single continuous servo, so that one button sends it one way and another button sends it the other way

    if (digitalRead(2) == HIGH) {
    servo1.writeMicroseconds(2000);
    delay(time_delay);
    servo1.writeMicroseconds(1500);

    if (digitalRead(2) == LOW) {
    servo1.writeMicroseconds(1000);
    delay(time_delay2);
    servo1.writeMicroseconds(1500);

    can you help ????

    • admin says:

      Change the code,

      // Button at input pin 2
      if (digitalRead(2) == HIGH) {
        servo1.writeMicroseconds(2000);
        delay(time_delay);
        servo1.writeMicroseconds(1500);
      }
      // Button at input pin 3
      if (digitalRead(3) == HIGH) {
        servo1.writeMicroseconds(1000);
        delay(time_delay2);
        servo1.writeMicroseconds(1500);
      }
      
  17. murali says:

    this is my last question, SIR,
    actually, i am developing sugar feeding system in my house, i am using screw conveyor 3d printing part .it will feed the sugar.in that i am using the ultrasonic sensor as the input signal when the signal is coming the continuous servo motor will start the rotating 2sec and then stop because giving the signal once i will get some quantity sugar. for this, i need the code. and thank you very much sir…

    • admin says:

      Try this. Here the servo operates when the object infront of the ultasonic sensor comes closer than the preset distance value.

      #include<Servo.h>
      const int  trig = 4, echo = 5 ;
      int Distance = 10; //Set preset distance value.
      Servo servo;
      void setup() {
        servo.attach(9);
      }
      void loop() {
        if (radar() < Distance) {
          // rotates clockwise at full speed
          servo.writeMicroseconds(1000);
          delay(20);
          // rotation stops
          servo.writeMicroseconds(1500);
        }
      }
      
      long radar(void)
      {
        digitalWrite(trig, HIGH);
        delayMicroseconds(15);
        digitalWrite(trig, LOW);
        long  dur = pulseIn(echo, HIGH);
        dur = dur / 58;
        return dur;
      }
      
  18. Lol says:

    Hello sir , i would like to control my servo , whereby the angld is controlled by potentiometer and the speed is controlled by pushbutton. Everytime the button is pushed , and after we release the button, when we play with potentiometer the speed will increase. My question is , for each speed , do i have to increase delay or decrease the delay? Because when i try increasing the delay, the speed increased

    • admin says:

      Actually, the value of delay between each servo values (increment or decrement) is inversely related to its speed. The speed increases with the decrease in delay. But in your case, you are controlling the servo position with a potentiometer, so in the code where you have added the delay..?
      Can you share the Arduino code.

  19. glenn says:

    Good day. Whats the code for. 1 servo controlled by two switches.First switch is going to 90′ while the 2nd switch will return it to its original position.

    • admin says:

      To move the servo through each angular degree, then Just change the position increment limit in the code; pos < 180 to pos < 90. Or the servo needs to move only two angles use, if (digitalRead(2) == HIGH ) {
       servo.write(90);
       delay(15);
      }
      if (digitalRead(3) == HIGH ) {
       servo.write(0);
       delay(15);
      }

  20. L1F3 says:

    good day sir.. just need some help.. whats the code for controlling a servo by a pushbutton manually. like 2 pushbutton. pb1 for left. and pb2 for right . then if i press pb1 it will move towards left but dont reach its maximum movement.. but only a microstep.. if i release it will stop. and only continue towards left if i press pb1 again.. then it will go towards right if anytime i press pb2 .. same as pb1

    • admin says:

      You mean to control servo movement right and left with a single step movement for each switch press.

      • Faran says:

        Actually I need the same help…!
        “You mean to control servo movement right and left with a single step movement for each switch press.”

        • admin says:

          Initialize all states as zero.

          //Increments the servo step.
          if (statep1 == 0 && digitalRead(p1) == HIGH) {
            statep1 = 1;
            pos += 10; // +10 - change the value to adjust the step.
            myservo.write(pos);
            delay(15);
          }
          if (statep1 == 1 && digitalRead(p1) == LOW) {
            statep1 = 0;
          }
          
          //Decrements the servo step.
          if (statep2 == 0 && digitalRead(p2) == HIGH) {
            statep2 = 1;
            pos -= 10; // -10 - change the value to adjust the step.
            myservo.write(pos);
            delay(15);
          }
          if (statep2 == 1 && digitalRead(p2) == LOW) {
            statep2 = 0;
          }
          
  21. Shruthi ns says:

    Sir I use three push buttons for controlling servomotor in 3 different angle how can I wrote this code please help me

    • admin says:

      you mean, to drive the servo position to just three angles while pushing the respective 3 switches.
      Eg:- switch 1 -> 45°.
      switch 2 -> 90°.
      switch 2 -> 135°.

  22. Manfred says:

    Hello Sir

    your code is magnificent for use on my model railroad thank you for that ,but i have a question can i moddefy this code so when it reaches 0 degree a green led wil turn on en wen it reaches 90 degree a red led turns ond and how can i do that

    kind regards from the netherlands

    • admin says:

      In this code, the Green LED ON when the servo position reaches 0 and the RED OFF. When 90 degree is reached the Green OFF and RED ON.

          //Place inside the end of first while loop;incrementing loop.
          if (pos == 90) {
            digitalWrite(REDLED, HIGH);
            digitalWrite(GreenLED, LOW);
          }
          //Place inside the end of second while loop;decrementing loop.
          if (pos == 0) {
            digitalWrite(GreenLED, HIGH);
            digitalWrite(REDLED, LOW);
          }
      
      • Manfred says:

        thank you very much

        • Manfred says:

          another question

          on what pin i should put de led on that i can`t find in this code

          thank you

          • admin says:

            You have to assign the variable REDLED and GreenLED with any of the digital pin numbers; the respective pin of arduino connected to the LEDs.

            const int REDLED = 4, GreenLED = 5; 
            
            void setup() {
              // set the digital pin as output:
              pinMode(REDLED, OUTPUT);
              pinMode(GreenLED, OUTPUT);
            }
            
  23. Manfred says:

    Dear Sir

    allready found the connection for the green and red led it works perfect

    THANK YOU

  24. Rathod Ronak says:

    Hello sir can you help me To make the code of TX of servo and Rx of servo it means use 2 push button as transmitter ( works as remote) and servo attached to the receiver portion of the prototype. This all system is made using Bluetooth HC-05.

    • admin says:

      Using a Bluetooth module, you have to use two Bluetooth modules and Arduino. One at the Transmitter and the other at the receiver end. Then using serial communication (TTL interface) you have to transmit the switch state or a value from the transmitter end to receiver end.
      First code (Tx) : switch press to serial data
      Second code (Rx) : serial to servo posistion.

  25. Rathod Ronak says:

    Yes sir I know how to connect Bluetooth as master and slave to each other but I m totally capable to write a code of servo using 2 push button as transmitter and 1 servo as receiver portion can u give me code of TX and Rx of my application. As per yr code of 2 push button

  26. Rathod Ronak says:

    Sorry I am NOT totally capable to write code of…………………..

    • admin says:

      Interface the arduino with hc-05 for bluetooth serial communication.

      //Reading push switch
      while (digitalRead(2) == HIGH && pos < 180) {
        pos++;
        // write value of variable pos to serial
        Serial.write(pos);
        delay(15);
      }
      while (digitalRead(3) == HIGH && pos > 0) {
        pos--;
        Serial.write(pos);
        delay(15);
      }
      
  27. Rathod Ronak says:

    Sorry sir but I can’t understand in the code of TX because there are potentiometer and I want to add 2 push button instead of potentiometer. And in your code of Rx you put 1 push button and with the help of this push button control the led. That’s I don’t understand.
    Now I just I request u is that please tell me wherever I will have to change in Code of TX and Rx as per my application. otherwise will you make the code of TX and Rx for me as per my application?

    Application :
    Servo rotate in CCW and CW using 2 push button (0-180___180-0). With the help of serial communication Bluetooth HC05.

    • admin says:

      Connect Tx and Rx of the HC-05 to the RX and Tx of the arduino respectively.

      //HC 05 Bluetooth module Receiver code
      #include <Servo.h>
      Servo servo;
      int Position = 0;
      
      void setup() {
        //Attach servo control pin to arduino pin 9
        servo.attach(9);
        Serial.begin(38400);
      }
      void loop() {
       if(Serial.available() > 0){ 
        // Read position value.
          Position = Serial.read();
       }
       // write values to servo
       servo.write(Position);
       delay(15); 
      }
      
      //HC-05 Bluetooth module Transmitter code
      int Position = 0;
      void setup() {
        Serial.begin(38400); 
      }
      void loop() {
        //connect push button to pin 2
       while (digitalRead(2) == HIGH && Position < 180) {
          Position++;
          //send 0 to 180
          Serial.write(Position);
          delay(15);
        }
        //connect push button to pin 3
        while (digitalRead(3) == HIGH && Position > 0) {
          Position--;
          //send 180 to 0
          Serial.write(Position);
          delay(15);
        }
      }
      
  28. Rathod Ronak says:

    OK thx sir

  29. Rathod Ronak says:

    Hello sir, I have motor driver = L298N, l293d, and A4988 this 3 drivers which one is most easy to control the stepper motor using 2 push button. And how to use these selected driver. Can you please explain with the help of code.

    Applications ;
    And I also control stepper motor using 2 push button using Bluetooth HC05

  30. Arthur says:

    Hello sir, i am totally new in programming a servo, i have a lilypad which i want to control 2 servos and push button as switch, i have make it to move bu using sweep code, but when change the angles it doea not do anything, after a few moves the servk stop and i hear a sound of servo still running and then servo feels hot,
    I onky want to achieve that my servo goes to go up 90 degrees by pressing the button switch and back to 0 by pressing again the switch.
    I really appreaciate all help i can get a coreect code. Thanks si much

    • admin says:

      Probably it can be due to gear damage or similar servo complaints. The heating is due to the excessive current drawn by the motors when it stuck.

  31. Arthur says:

    Btw sir my servos are attached to pin 7 and 9, i alao intend to use 6 volts battery pack, i qas told that i need a separate skurce for the servos i want them to move at the same time same angle and back.

  32. Rathod Ronak says:

    Can YOU make this code as per my application Rx and TX for me
    Sir I req you.

    Application:
    Control the stepper using 2 push button using Bluetooth HC05

  33. Rathod Ronak says:

    hello sir i make this code to contorl stepper motor using 2 pushbotton with help of l298n driver.
    so i request i is that can you make this BELOW code for me into RX and TX for BLUETOOTH HC-05.

    i hope you help me.

    #include

    int forward = 2;
    int reverse = 3;

    Stepper motor(200, 11,10,9,8);

    void setup() {
    pinMode(forward,INPUT);
    pinMode(reverse,INPUT);
    Serial.begin(9600);
    }

    void loop() {
    int Speed = analogRead(A0);
    int RPM = map(Speed, 0, 1023, 0, 500);
    int f = digitalRead(forward);
    int r = digitalRead(reverse);
    if(f == 1 && r == 0 && RPM > 1)
    {
    motor.step(1);
    motor.setSpeed(RPM);
    delay(.01);
    }
    if(r == 1 && f== 0 && RPM > 1)
    {
    motor.step(-1);
    motor.setSpeed(RPM);
    delay(.01);
    }
    delay(5);
    Serial.println(RPM);
    }

    • admin says:

      I think this is the code you are expecting.

      //Receiver code
      #include <Stepper.h>
      Stepper motor(200, 11, 10, 9, 8);
      void setup() {
        Serial.begin(38400);
      }
      void loop() {
         while (Serial.available() > 0)
            {
          int pos = Serial.parseInt();   
          int RPM = Serial.parseInt();   
        }
        motor.step(pos);
        motor.setSpeed(RPM);
        delay(10);
      }
      
      //Transmitter code
      int forward = 2;
      int reverse = 3;
      void setup() {
        pinMode(forward, INPUT);
        pinMode(reverse, INPUT);
        Serial.begin(38400);
      }
      void loop() {
        int Speed = analogRead(A0);
        int RPM = map(Speed, 0, 1023, 0, 500);
        int f = digitalRead(forward);
        int r = digitalRead(reverse);
        if (f == 1 && r == 0 && RPM > 1)
        {
          Serial.print(1);
          Serial.print(",");
          Serial.println(RPM);
          delay(10);
        }
        if (r == 1 && f == 0 && RPM > 1)
        {
          Serial.print(-1);
          Serial.print(",");
          Serial.println(RPM);
          delay(10);
        }
        delay(5);
        Serial.println(RPM);
      }
      
  34. Rathod Ronak says:

    OK thx sir if you don’t mind can u please give me mail I’d or contact number

  35. Rathod Ronak says:

    hello sir my name is ronak rathod .
    i mail you to solve my query. i request you please check out your mail and help me .

  36. Swanith says:

    Hello I want to make servo move from 90 to 140 if first button is pressed and come back to 90 if second button is pressed and it should move from 90 to 40 if third button is pressed and again if second button is pressed it should go back to 90. I want connection and code. Pls HELLLLPPPPPP. HHHHHEEEEELLLLLLLPPPPPP

  37. Rathod Ronak says:

    Sir please please sir help me. ‘ગ’ word write by mistake at the and of code.

  38. Rathod Ronak says:

    No sir but signal not approach at the receiver portion. And in the transmitter portion only show the value of ‘A0’ when I open serial monitor. There is no problems in the Bluetooth I checked perfectly.

    • admin says:

      I think you need to sort out the issue step by step.
      Check the communication using the Bluetooth module by directly sending data. And make sure it is properly communicating.
      Then step by step build the code by adding you sensor reading etc. Separately check each portion.

  39. Rathod Ronak says:

    Hello sir can you you please help me? As per my above application or solve this problem

  40. Rathod Ronak says:

    Hello sir can you you please help me? To solve my this problem

  41. Jerry Piaskowy says:

    how is the code different on an arduino mega 2560? thanks!!!

  42. Rathod Ronak says:

    Hello sir I want to control 2 servo motor using 4 push button, each servo control by 2 push button. It means 1st servo control by 2 push button and 2nd servo control by other 2 push button. This all system is control by Bluetooth HC05 then I request u plz help me

    This code was u gave me before months ago. Then can u plz give me code as per my above application.

    //HC 05 Bluetooth module Receiver code

    #include
    Servo servo;
    int Position = 0;

    void setup() {
    //Attach servo control pin to arduino pin 9
    servo.attach(9);
    Serial.begin(38400);
    }
    void loop() {
    if(Serial.available() > 0){
    // Read position value.
    Position = Serial.read();
    }
    // write values to servo
    servo.write(Position);
    delay(15);
    }

    //HC-05 Bluetooth module Transmitter code

    int Position = 0;
    void setup() {
    Serial.begin(38400);
    }
    void loop() {
    //connect push button to pin 2
    while (digitalRead(2) == HIGH && Position < 180) {
    Position++;
    //send 0 to 180
    Serial.write(Position);
    delay(15);

  43. XomenX says:

    Hallo admin, can youbplease help me.
    I have project rfid servo door lock, please help cooding for it.
    If i touch the rfid, servo will going from 0 to 90 but it will stay in ther, and if touch the rfid again, servo will going from 90 to 0.
    I need your support please

    • admin says:

      For controlling a servo with RFID you need to modify the code given above to check whether the RFID code given is correct, instead of checking the state of the digital input to drive the servo. Do you have the remaining code for reading and verifying UID?

  44. Rathod Ronak says:

    Hello sir I want to control 2 servo motor using 4 pushbutton each servo motor is controlled by 2 pushbutton with the help of HC-05 BLUETOOTH module. Sir can u please help to make a code

  45. crocker says:

    How do I add 2 LED’S to the circuit . All I have is a 1k ohm resistor and my Servo makes a humming noise sometimes. When I make Servo go clockwise LED turn red on. Then when press button 2 counterclockwise and turn green LED on.

    • admin says:

      Use this code,

      //Declare Pin 4 & 5 as output, in void setup.
      while (digitalRead(2) == HIGH && pos < 180) {
        // Red LED to pin 4
        digitalWrite(4, HIGH); // RED ON
        ...
        ...
      }
      digitalWrite(4, LOW); // RED OFF
      while (digitalRead(3) == HIGH && pos > 0) {
        // Green LED to pin 5
        digitalWrite(5, HIGH); //Green ON
        ...
        ...
      }
      digitalWrite(5, LOW); //Green OFF
      
  46. crocker says:

    I have the code I. How do I add 2 LED’S to the circuit . All I have is a 1k ohm resistor and my Servo makes a humming noise sometimes. When I make Servo go clockwise LED turn red on. Then when press button 2 counterclockwise and turn green LED on?

    • admin says:

      As two LEDs are not ON at a time, you can use either one of the circuits.
      arduino parallel LED one resistorMultiple LEDs on a Single Resistor
      The servo buzzing can be due to positioning error or any mechanical issues.

  47. crocker says:

    l’m new
    I still cannot get it to work can you make a whole new diagram like the one above

  48. crocker says:

    like the original one

  49. RR says:

    can i use 2 push buttons which have 2 pins under to connect to the breadboard? if can, how do i connect it?

  50. chinta jyothi says:

    HELLO,
    i am using micro servo motor 9g A0090 and i need to modify it to turn 360 so i removed the knob inside the servo and it is rotating 360.but the problem is the servo is rotating continuously with out stop.i need angle control with push button .plz help me to solve this

    • admin says:

      The feedback system in the servo is for 180 degrees. So, you cant operate a 360 degree angle control with that.

  51. Cami says:

    Hi! Do you know what should I do if I need to use a DC motor?

  52. mohammad says:

    hi guys,,i want controll mq5 sensor with butoon,or bluetooth, does anyone know the program?

  53. Bartek says:

    Hi, I have try to edit a code to work with two servos by one button attached to a servo and only one is working correct. Can someone write my code correctly? while (digitalRead(2) == HIGH && pos1 0) {
    pos1–;
    servo.write(pos1);
    delay(15);

  54. subhomoy karmakar says:

    can we control ones input as aswitch of servo motor with help of arduino; use ones output to control servo motor.
    can we control servo motor clockwise and anti-clock wise with a single pulse with help of arduino.

    • admin says:

      Did you mean to rotate the servo clockwise and counterclockwise with alternate pulses?
      That is, the servo moves in one direction when the switch is pressed first and moves opposite when pressed again.

  55. Pawel says:

    Hi, i have some trouble how to properly send signal from buttons by nrf24L01 module. Which code must be on transmitter, which on receiver? Can u help me ?

    • admin says:

      digitalRead at TX part and servo write at the RX part.
      From the transmitter, you have to generate corresponding messages for the inputs and read the message at the receiver for servo write.

  56. Maura says:

    Hello, I am new to Arduino and coding and I would like to control my servo with one push button. With one push I would like it to sweep from 0 to 180 degrees and stop there and then with a second push I would like it to sweep back from 180 to 0. I have been playing around with code and cannot seem to figure out how to exactly do this. Any input would be extremely helpful, thank you very much!

    • admin says:

      Try this code. The servo sweeps between 0 and 180 degrees (0 → 180 | 180 → 0) for alternate switch press.

      //you have to add,
      int state = 0, Loadstate = 0;
      const int Switch = 2;
      
      //Inside void loop
      if (state == 0 && digitalRead(Switch) == HIGH) {
        state = 1;
        //Load state toggles between high and low for each switch press
        Loadstate = !Loadstate;
      }
      if (state == 1 && digitalRead(Switch) == LOW) {
        state = 0;
      }
      if (Loadstate == HIGH) {
        //Sweep from 0 to 180, when first push set Loadstate = HIGH.
        for (pos = 0; pos <= 180; pos += 1) {
          myservo.write(pos);
          delay(15);
        }
        else {
          //Sweep from 180 to 0, when second push set Loadstate = LOW.
          for (pos = 180; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(15);
          }
      
      • Maura says:

        Hi, thanks for the input! I still seem to be having trouble with the servo control, it is not switch activated at all now and just sweeping when using this code, even though I am declaring the switch and appropriate pin. Any idea why this is doing that?

        • admin says:

          Can you share the full code you are using?
          Also, are you sure you have a properly connected pull-down resistor?

  57. fermin isidro says:

    quien me puede ayudar con un programa en arduino me urgue es controlar un servo con 4 pus boton con el primero me tiene quedar a 45° y con el 4 boton regresar a cero, y con el boton 2 me de 90° y con el 4to boton regresar a 0, y con el 3 boton mandar a 180° y con el 4to boton regrece a cero me urgue dejo mi email y podemos apoyarnos. tiene que ser antes del 16 agosto 2019. ferpab_80@hotmail.com

    • admin says:

      Try this,

      if (digitalRead(1) == HIGH ) {
        servo.write(45);
      }
      if (digitalRead(2) == HIGH ) {
        servo.write(90);
      }
      if (digitalRead(3) == HIGH ) {
        servo.write(180);
      }
      if (digitalRead(4) == HIGH ) {
        servo.write(0);
      }
      
  58. Jaseem says:

    Sir, do this code work as:
    when pb1 is pressed the servo (i am using continuous servo) moves till the button remains pressed upto 180 and when pb2 is pressed servo rotates back till button is pressed upto 0, and in case the button is released earlier then the rotation stops at same time

    • admin says:

      Actually the position of the continuous servo is not determined by the input as like a standard servo motor; no end position in either direction. You can only control the speed and direction of rotation.
      Refer comments https://mechatrofice.com/arduino/servo-motor-push-button-control#comment-515

      Use this code to rotate a continuous servo clockwise and counterclockwise with switch press.

      if (digitalRead(p1) == HIGH) {
        // when switch p1 is pressed rotates clockwise at full speed.
        servo.writeMicroseconds(1000);
      }
      else(
        // rotation stops when released
          servo.writeMicroseconds(1500); 
      }
      if (digitalRead(p2) == HIGH) {
      // when switch p2 is pressed rotates counter clockwise at full speed.
      servo.writeMicroseconds(2000);
      }
      else(
         // rotation stops when released
          servo.writeMicroseconds(1500); // rotation stops
      }
      
  59. JKAWPB says:

    Hey admin,

    You seem like the most helpful Arduino pro on the internet. Maybe you could help me also?!

    I’m very new to Arduino. I’m looking for help with coding and wiring. I have an Arduino Uno, an MG995 servo, three momentary push button switches, a bunch of different resistors, and a separate power supply for the servo.

    When I press button 1, I would like the servo to rotate clockwise from 0 degrees to 45 degrees, stay there for 30 seconds, then rotate counter-clockwise from 45 degrees to 0 degrees (return to the original position).

    When I press and hold button 2, I would like the servo to rotate clockwise from 0 degrees to 45 degrees and stay there until I release button 2. When I release button 2, the servo should to the original position.

    When I press button 3 at any time (during the 30 second interval mentioned above), I would like the servo to return to the original position.

    I will also need a proper wiring diagram that would accompany the above sketch… please.

    • admin says:

      Add this code inside the void loop. For the circuit just refer the sketch given in the main content. You just need to add one more switch as same as switch 1 & 2 (one terminal of the switch to +Vcc and the other to arduino pin with a pull down resistor which is connected across the arduino pin and GND) and connect to the pin 4 of the arduino.

      /*Switch 1 - connected to Arduino pin 2.
        Switch 2 - connected to pin 3.
        Switch 3 - connect to pin 4.*/
      if (digitalRead(2) == HIGH) {
        // Once you press the switch 1 the servo write to 45 deg.
        servo.write(45);
        int T2 = millis();
        while (millis() - T2 <= 30000 && digitalRead(4) != HIGH) {
          // Loop repeats for 30 seconds unless switch 3 is pressed.
        }
        // if switch 3 is pressed, while loop exits and servo write to 0 deg.
        servo.write(0);
      }
      // when switch 2 is pressed servo write to 45.
      if (digitalRead(3) == HIGH) {
        servo.write(45);
      }
      // Servo write to 0 only when switch 2 is released.
      else {
        servo.write(0);
      }
      

      The code is not tested with a circuit. You just try and if any error occurs, please let us know; ll helps you.

  60. DEVIL says:

    my project is a rfid card controled servo thAT will be came at the first position after 5 sec and the same servo can controled with push button for forward and backward PLEASE HELP ME AMIGO

    • admin says:

      You mean to turn the servo to 0 when RFID is detected and after 5 seconds the servo control switches to switch input. Right.

  61. Lintang says:

    Sir can you help me.
    I have 2 servo with 3 push button with different rotate.
    Servo1 rotate 0 to 60 and back 60 to 0 with interval per degree and repeat automatically (have push button on off)
    Servo 2 rotate 0 to 60 if push button 1 clicked, and if push button click again will back 60 to 0.
    Pls help me how to make that script

  62. mike says:

    Hi, I am looking for some code to do this four button and one servo
    servo starts at 0 deg from start
    Press button 2 servo goes to position 90 deg
    Press button 3 servo goes to position 180 deg
    Press button 3 servo goes to position 270 deg
    Press button 1 servo goes to position 0 deg

    pressing button 1 will reset the position to 0 deg
    or pressing button 1 – 2 – 3 – 4 will take up the assigned deg

    It must not go over centre, say from 270 deg straight to 0 deg but travel the same track, the reason for this is the servos are rotating a small platform, the platform has wires attached to it, so, if it did the wires would get twisted up around the centre.
    I will be using a 270 deg servo for this.
    I do know that to get the degrees i need i will have to change the code to get the rotational positions of the servo
    can any one help please

    Mike

    • admin says:

      I think your concern is about the servo continues the same direction of rotation from 0 to 270 and to 0, which makes a full rotation on each time and makes your wires keep twisted. But a 270-degree servo never rotates after 270 it stops at the maximum angle and for any angle value below that, it rotates in the reverse direction.

  63. mike says:

    Hi, yes I found that out.. I have muddled through code an have something that works, I do need some one to scan though it and tidy it up s bit. The other thing that is needed is LEDs to indicate the button press ie what position the servo is and button pressed these remain on untill a new position is taken up
    Mike

    • admin says:

      you can add “digital write” off and on along with the servo write, to turn on and off LEDs with the corresponding buttons.

  64. mike says:

    Hi, I have made the code for 4 buttons and one servo, seems to work, I still need help on the LEDs so I can see the angle position the servo it is at, so at 90deg led is on, 180 led is on and so on

    • admin says:

      Just add “digitalWrite(pin,HIGH);” at each “if” condition for input switch.
      Example for 90 deg,
      if (digitalRead(2) == HIGH) {
      digitalWrite(6,HIGH); //Connect LED of 90deg to pin 6
      digitalWrite(pin,LOW); //Add this line for every other pins to turn off.
      ….
      ….
      servo.write(90);
      }

  65. Cole says:

    Hi, I’m very new to arduino’s and coding, but I was just wondering if you could help me. I’m trying to get a servo to go from 0 to 45 degrees when I push a button then back to 0 when I release it. Is there a way to do this?

    • admin says:

      Use the below code inside the void loop,
      // simply the servo arm rotates to 45 degrees when the button is pressed.
      if (digitalRead(2) == HIGH) {
      servo.write(45);
      delay(50);
      }
      // Whenever it is released its goes to 0 degree.
      else{
      servo.write(0);
      delay(50);
      }

  66. Cole says:

    What would the void setup be?

    • admin says:

      #include <Servo.h>
      void setup() {  
      pinMode(2, INPUT);  
      servo.attach(9);
      }
      void loop() {
      ……….
      ……….
      }

  67. Jasmin says:

    Hello Sir.
    Can you write me a code for for two buttons Function.
    When i press a button 1 it goes from 0 to 65 degrees and returns to 0 in full speed end stops for two seconds. That repeats all the time when Button 1 ist pressed.
    when i press Button 2 (Taster) and releas goes from 0 to 65 degrees and returns to 0 in full speed. It waits there till next time is Button 2 Pressed.

    • admin says:

      void loop() {
      if (digitalRead(2) == HIGH) { // Button 1
      servo.write(65);
      delay(50);
      servo.write(0);
      delay(2000); // 2 Second delay
      }
      if (digitalRead(3) == HIGH) { // Button 2
      servo.write(65);
      delay(50);
      servo.write(0);
      } }

      • Jasmin says:

        Thank you wery much for Replay.
        I have tried and what the Problem is that the sequens starts imidietly without pressing any Buttons.
        What do i have to enter that Action taks only when Button is Pressed els no movment.
        And by Button 2 i have to releas Button to go back to position 0. I want when i Press and releas that goes from 0 to 65 and back to 0 and wait till next Button is Pressed.
        Thx in advance…

        • admin says:

          You mean,
          When pressed switch 1, 0 -> 65 -> 0 and 2s delay, then repeats.
          When pressed switch 2, 0 -> 65. When released switch 2, 65 -> 0 else remain at 65.

          void loop() {
          if (digitalRead(2) == HIGH) { // Button 1
          servo.write(65);
          delay(50);
          servo.write(0);
          delay(2000); // 2 Second delay
          }
          if (digitalRead(3) == HIGH) { // Button 2
          servo.write(65);
          delay(50);
          } else {
          servo.write(0);
          delay(50);
          }
          }
          If the sequence is starting immediately without pressing any Buttons, then you must check whether you have properly conencted the pull down resitors and declared pin 2 and 3 as inputs.

  68. Zoey m says:

    Hi there! First of all thank you for all of your support. I am trying do build a puzzle with 5 servos and 5 push buttons where:

    Button A – Press one time – Servo A moves to 20
    Button A – Press second time – Servo A moves to 90
    Button A – Press third time – Servo A moves to 150
    Button A – Press fourth time – Servo A moves back to initial position 0.
    —–

    Button B – Press one time – Servo A & Servo B moves to 20
    Button B – Press second time – Servo A & Servo B moves to 90
    Button B – Press third time – Servo A & Servo B moves to 150
    Button B – Press fourth time – Servo A & Servo B moves back to initial position 0.

    ——-

    Button C – Press one time – Servo A & Servo B & Servo C moves to 20
    Button C – Press second time – Servo A & Servo B & Servo C moves to 90
    Button C – Press third time – Servo A & Servo B & Servo C moves to 150
    Button C – Press fourth time – Servo A & Servo B & Servo C moves back to initial position 0.

    —-

    Button D – Press one time – Servo A & Servo B & Servo C & Servo D moves to 20
    Button D – Press second time – Servo A & Servo B & Servo C & Servo D moves to 90
    Button D – Press third time – Servo A & Servo B & Servo C & Servo D moves to 150
    Button D – Press fourth time – Servo A & Servo B & Servo C & Servo D moves back to initial position 0.

    I have can only make the first section where Button A & Servo A works accordingly, but as soon as I add Part B the nothing happens.
    Can you please help me with that? thank you so much!!!

  69. Ryan says:

    Hi, I am trying to make a servo go clockwise with the push of a button and counterclockwise with the push of another button. Do you think that you can help me with the circuit and code?

  70. Kasthuriarachchi says:

    Dear could you please Do a lesson about watch dog time and sleep mode in Arduino.

  71. priyam patel says:

    Create a system for speed control of a Servo Motor using two buttons. Whenever the
    first button is pressed the speed should increase gradually and speed should reduce
    on the second button. The second button will have a higher priority if both are
    pressed. Find the percentage error and accuracy.

  72. anto jose says:

    sir,
    I need 4 servos (5v) running , so which is better Arduino uno or Arduino nano.

    will I need extra module for driving the servos.

    I also need the code for running 2 of the servos from 0 to 80 degree followed by the other 2 to go 0 to 45 degree when I press a push button and then when I press the button again I need the second set of servos to return to 0 degree followed by the first set. can u help me ?

    • admin says:

      Uno and nano have almost the same specifications both run with atmega328p, for your project it doesn’t make any difference.
      You can drive 4 servos using uno or nano alone, but you have to (5V)power the servos externally since you have 4 servos.
      In your program, what exact movements you are required? just move the separate set in order on alternate switch press or when keep holding the switch? do they have a specific difference in time between the two sets? (could you detail the algorithm)

  73. Philippe says:

    How can i change the program to press once the buton and tourn 45 drees? for each side

    • admin says:

      if(digitalRead(2) == HIGH) {
      servo.write(45);  
      }
      else if(digitalRead(3) == HIGH) {
      servo.write(0); }

      • Bond Osman says:

        Have a Gold life my friend. I am work with a project , you are help for too many people, its great.

        I have 2 button , servo and lm35. Fırst ı want a degree for temp then servo work for hım bring it temp for mu degree.
        Are you have idea for this ?

        • admin says:

          Could you explain this further?

          • Bond Osman says:

            There is hot and cold water interference, I have 2 different channels and valves, like the valve. I want to use the output degree, I want to change the servo degree for the water degrees. I guess I should use pid control. But I can’t use the pid code. Can you help me

          • admin says:

            You mean, you have to control the valves of hot and cold water to obtain the required water temperature?

  74. Bond Osman says:

    Yes exactly. Are you have any idea ?

    • admin says:

      How do you need to control that?
      By manual switch pressing to turn the servo position. Or automatically for an input temperature value?
      Do you have 2 separate servos for two valves?

  75. JTP says:

    Hello, I’d love some help if you don’t mind. You seem very knowledgable with this stuff and I’m a beginner lol

    So I’m trying to make a spinning pencil holder that’s controlled by 2 buttons, one for left one for right. If you press one, the stepper motor with spin a certain amount to reveal a pencil. I want it to only spin that amount in that direction each time, but I can’t find any code for it!! I have an Arduino Uno with the stepper motor already on its own circuit board. Any chance you have either schematics or code for making this work?

    I also may not have described this the best way, so if you need more detail let me know lol, I’m not great with words.

  76. MJO says:

    I’ve read through all of the comments and have been trying to figure out this code, but have only gotten it to work with one servo. And was wondering if you could help me out.

    My goal is to have two servos controlled by one button. Both servos start at 0° then when the button is pressed both servos turn to 90° simultaneously and when pressed simultaneously go back to 0°. Any help is greatly appreciated!

    Thank you!!!

  77. Char says:

    Hey is there a way that I could use this code, but replace the push buttons with hand sensors?

    • admin says:

      Yes of course you can replace it with any input. But code and the circuit are completely dependent on the sensor and its operation.

  78. Kevin Rodz says:

    hi admin, i would be so grateful if you could help me with this problem, im trying to use a servo with 2 pushbuttons, one for going up and another for going down, pushing the UP button only once and the servo going up 90 degrees, then if pushed again, going to 180 degrees. Then if the downbutton is pushed the servo moves from 180 to 90, and if pushed again from 90 to 0. Being 0 degrees the min and 180 the max. Kind of simulating a type of elevator but not at small increments,instead going straight from one angle to another. Thanks in advance!

    • admin says:

      Try this code, the code checks the state of the buttons, and when a button is pressed, it increases or decreases the servoPosition variable accordingly and moves the servo to the desired angle.

      if (upButtonState == LOW) {
      delay(50); // Debounce the button
      if (digitalRead(upButtonPin) == LOW) {
      // Increase the servo position
      servoPosition += 90;
      if (servoPosition > 180) {
      servoPosition = 180;
      }
      elevatorServo.write(servoPosition);
      delay(200); // Delay for button release
      }
      }

      // Check if the DOWN button is pressed
      if (downButtonState == LOW) {
      delay(50); // Debounce the button
      if (digitalRead(downButtonPin) == LOW) {
      // Decrease the servo position
      servoPosition -= 90;
      if (servoPosition < 0) { servoPosition = 0; } elevatorServo.write(servoPosition); delay(200); // Delay for button release } }

Leave a Reply

Your email address will not be published. Required fields are marked *