搜索代码

Control a Servo Motor with a Push Button: Move Servo in One Direction SPB-2

Control a Servo Motor with a Push Button: Move Servo in One Direction SPB-2

Control a Servo with a Push Button Toggle on Arduino

Welcome to this Arduino project guide where you will learn how to control a servo motor using a single push button. This simple yet powerful setup allows you to toggle the servo's position between two defined angles. With each press of the button, the servo will smoothly sweep from its current position to the opposite limit and then stop, waiting for the next command. This functionality is perfect for projects that require opening/closing a latch, moving a robotic arm to a set position, or any application needing a two-state mechanical switch.

This guide will cover the hardware, wiring, and a detailed explanation of the Arduino code. The start and end angles are fully customizable, allowing you to set a full 0-180 degree sweep or a much smaller range like 50-110 degrees, as shown in the video.


Understanding the Servo Motor

A servo motor is a special type of motor that allows for precise control of its shaft's angular position. Most standard hobby servos, like the SG90 (plastic gear) or the high-torque MG996R (metal gear), have a range of motion of 180 degrees. They use a standard 3-wire connection, which is crucial for wiring them correctly, as explained at 03:23 in the video.

  • Ground Wire: Usually Brown or Black. Connects to the Arduino's GND pin.
  • Power Wire (VCC): Always the middle wire, typically Red. Connects to the Arduino's 5V pin.
  • Signal Wire: Usually Orange or White. This wire receives the control signal from the Arduino and must be connected to a PWM-capable pin (marked with a tilde `~`).

Hardware and Wiring

For this project, you will need an Arduino, a servo motor, a standard push button, and a few connecting wires. The wiring is simple and is detailed in the video at 04:02.

The push button is connected to pin 2 and GND. The servo's signal wire is connected to pin 3, which is a PWM pin. The servo is powered directly from the Arduino's 5V and GND pins.

Wiring diagram for connecting a servo motor and a push button to an Arduino.

The Arduino Code Explained

The code uses the standard Servo.h library, which comes built-in with the Arduino IDE, so no external downloads are needed. The logic is designed to start the servo's movement when the button is pressed and stop it automatically once it reaches its target angle. A detailed walkthrough begins at 05:14 in the video.

User Configuration

At the top of the sketch, you can easily customize the servo's behavior by changing a few key variables.


#include <Servo.h>

Servo myservo;  // create servo object

#define servoPin 3      // Arduino pin connected to servo signal wire (must be PWM)
#define pushButtonPin 2 // Arduino pin for the push button

int angle = 90;           // The initial angle for the servo when it starts
int angleStep = 5;        // The increment for each step (controls speed)
const int minAngle = 50;  // The first target angle
const int maxAngle = 110; // The second target angle
  • servoPin: The pin for the servo's signal wire. Make sure it's a PWM pin (like 3, 5, 6, 9, 10, or 11 on an Arduino Uno).
  • angleStep: This controls the speed of the servo's sweep. A larger value (e.g., 10) will make it move faster, while a smaller value (e.g., 1) will make it move slower and more smoothly.
  • minAngle and maxAngle: These define the two positions the servo will toggle between. For a full range of motion, you can set these to 0 and 180.

The `setup()` Function

The setup() function initializes the serial communication for debugging, attaches the servo to its pin, and configures the push button pin.


void setup() {
  Serial.begin(9600);
  myservo.attach(servoPin);
  pinMode(pushButtonPin, INPUT_PULLUP); // Configure the button pin
  Serial.println("Robojax Servo Button ");
}

Notice the use of INPUT_PULLUP. This activates an internal resistor in the Arduino, which "pulls" the pin's voltage high. This clever trick eliminates the need for an external pull-up resistor in your wiring.

The `loop()` - Core Logic

The main loop waits for a button press. Once pressed, it sets a flag (buttonPushed = 1) that initiates the servo's movement.


void loop() {
  // Check if the button is pressed (LOW because of INPUT_PULLUP)
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }

  // If the button has been pushed, start moving the servo
  if(buttonPushed){
    // Increment the angle by the step value
    angle = angle + angleStep;

    // If the servo reaches either limit...
    if (angle <= minAngle || angle >= maxAngle) {
      // Invert the step direction for the next press
      angleStep = -angleStep;
      // Stop the servo's movement until the next press
      buttonPushed = 0;
    }
    
    myservo.write(angle); // Send the new angle to the servo
    delay(100); // A short delay to allow the servo to move
  }
}

The clever part of the logic happens when the servo reaches one of its limits (either minAngle or maxAngle). At that point, two things happen: the angleStep is inverted (e.g., from +5 to -5), reversing the direction for the next movement, and the buttonPushed flag is reset to 0, which stops the servo until you press the button again.


Uploading and Testing

With the circuit wired and the code configured, upload the sketch to your Arduino. When it starts, the servo will move to its initial position.

Now, press the button once. The servo will sweep to one of its target angles and stop. Press the button again, and it will sweep back to the other target angle and stop. You have successfully created a servo toggle switch!

271-Code #2 controlling servo motor
语言: C++
/*
 Controlling a servo with Push button with Arduino
 this is code #2 to control servo with push button by Robojax (Robojax.com )

code #1 when push button the servo goes from 0° to 180° (or set your angle) and returns back
    Watch video for code #1: https://youtu.be/fPrPRZlGdvA
code #2 when push button the servo goes from either from 0° to 180° or from 180° to 0° (or set your angle)
    Watch video for code #2: https://youtu.be/T2HMJiy9b_I
code #3 when push button pressed AND keep pressed the servo goes from 0° to 180° (or set your angle)
    Watch video for code #3:https://youtu.be/58Qqh60FrMU 
code #4 two Push button used one is used to move servo to LEFT direction and the other for RIGHT direciton 
    Watch video for code #4: https://youtu.be/_uz7YcOzvjU
    

 *  
 * Written by Ahmad Shamshiri for Robojax Video channel www.Robojax.com
 * Date: Dec 13, 2018 at 23:39  in Ajax, Ontario, Canada
 * Permission granted to share this code given that this note is kept with the code.
 * 
 * Disclaimer: this code is "AS IS" and for educational purpose only.
 * this code has been downloaded from https://robojax.com
 
 * Get this code and other Arduino codes from Robojax.com
Learn Arduino step by step in structured course with all material, wiring diagram and library
all in once place. Purchase My course on Udemy.com http://robojax.com/L/?id=62

****************************
Get early access to my videos via Patreon and have  your name mentioned at end of very 
videos I publish on YouTube here: http://robojax.com/L/?id=63 (watch until end of this video to list of my Patrons)
****************************

If you found this tutorial helpful, please support me so I can continue creating 
content like this using PayPal http://robojax.com/L/?id=64

 *  * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact 
 * This code has been download from Robojax.com
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2 

int angle =90;    // initial angle  for servo
int angleStep =5;
const int minAngle = 50;
const int maxAngle = 110;

int buttonPushed =0;

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

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // 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 <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    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
   }

  
}

资源与参考

尚无可用资源。

文件📁

没有可用的文件。