Control Servo with Push buttons using Arduino

Project Video
Project Details

This is Arduino code to control a servo using push button and Arduino. For step by step details please watch video.

See Control Servo with two push buttons with Arduino code 2/2

Servo control with push button Arduino sketch

Project Code


 /*
 Controlling a servo with Push button with Arduino
 when a push button is pressed, the servo start moving to the right or left until
 reachers 180 and then returnes to 0 degree.

 May 22, 2018 at 01:00 
 Written by Ahmad Shamshiri for Robojax.com in Ajax, Ontario, Canada
 Watch video for this code at https://youtu.be/7woqNH_qby4
 This code is taken from http://robojax.com/learn/arduino
*/

#include 

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

int angle =90;    // initial angle  for servo
int angleStep =10;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(2,INPUT_PULLUP);
   Serial.println("Robojax Servo Button ");
}

void loop() {
  while(digitalRead(2) == LOW){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= 0 || angle >= 180) {
      angleStep = -angleStep;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");    
  delay(100); // waits for the servo to get there
  }// while

  
}

If you found this Arduino course helpful, please support me so I can continue creating content like this. support me via PayPal