Этот учебник является частью: Сервомоторы
Здесь перечислены все видеоролики, связанные с сервомоторами. Ссылки на другие видео находятся ниже этой статьи.
Control a Servo Motor with a Push Button: Move Servo and Return SPB-1
In this tutorial, we will learn how to control a servo motor using a push button. When the button is pressed, the servo will move from its initial position to 180 degrees and return back. This project highlights the practical application of servos in various automation tasks, making it an essential skill for hobbyists and engineers alike. For a clearer understanding, you can also refer to the video (in video at 00:00).
Hardware Explained
The primary components used in this project are the servo motor and a push button. The servo motor is a specialized motor that can precisely control its position within a limited range, usually 0 to 180 degrees. It has three wires: ground, power (typically 5V), and a signal wire that receives control signals from the Arduino.
The push button serves as a simple input device that allows the user to interact with the system. When pressed, it sends a signal to the Arduino, which triggers the movement of the servo motor. This interaction is straightforward yet powerful, enabling various applications in robotics and automation.
Datasheet Details
| Manufacturer | Generic |
|---|---|
| Part number | SG90 |
| Logic/IO voltage | 5 V |
| Supply voltage | 4.8–6 V |
| Output current (per channel) | ~1 A |
| Peak current (per channel) | ~2 A |
| PWM frequency guidance | 50 Hz |
| Input logic thresholds | 0.2 V (LOW), 2.0 V (HIGH) |
| Voltage drop / RDS(on) / saturation | ~0.5 V |
| Thermal limits | 85 °C max |
| Package | Standard |
| Notes / variants | Metal gear versions available |
- Ensure voltage supply is within 4.8–6 V for optimal performance.
- Connect the ground wire to the Arduino GND.
- Use PWM-capable pins for signal input.
- Monitor the servo's temperature; do not exceed 85 °C.
- Use proper pull-up resistors when connecting buttons without built-in pull-ups.
Wiring Instructions

To wire the servo motor and push button, start by connecting the servo motor's ground wire (usually brown or black) to the GND pin on the Arduino. Next, connect the middle wire (typically red) to the 5V pin on the Arduino for power. The signal wire (often orange or yellow) should be connected to pin 3 on the Arduino.
For the push button, connect one pin to the GND and the other pin to pin 2 on the Arduino. This setup uses the internal pull-up resistor, so there’s no need for an external resistor. Ensure that the button is functioning properly by checking the connections before powering up the system.
Code Examples & Walkthrough
The program begins by including the Servo library, which simplifies the control of the servo motor. An instance of the Servo class is created named myservo, which will control the motor. The pin for the servo is defined as 3, and the push button pin is defined as 2.
#include
Servo myservo; // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2
int angle = 90; // initial angle for servo (between 1 and 179)
In the setup function, we initialize the serial communication with Serial.begin(9600) and attach the servo to the defined pin. The initial position of the servo is set with myservo.write(angle), which places it at 90 degrees.
void setup() {
Serial.begin(9600); // setup serial
myservo.attach(servoPin); // attaches the servo on pin 3 to the servo object
pinMode(pushButtonPin, INPUT_PULLUP);
myservo.write(angle); // initial position
}
In the loop function, the program continuously checks the state of the push button. If the button is pressed, it updates the angle by adding angleStep. If the angle exceeds the defined limits, it reverses the direction of movement.
void loop() {
if(digitalRead(pushButtonPin) == LOW){
buttonPushed = 1;
}
if (buttonPushed) {
angle += angleStep;
if (angle >= maxAngle) {
angleStep = -angleStep;
}
myservo.write(angle); // move the servo to desired angle
delay(100); // waits for the servo to get there
}
}
By using this code, the servo motor will respond to the push button, moving between the defined angles. If you want to see the complete code, it will load below the article.
Demonstration / What to Expect
When you press the button, the servo motor should move smoothly from its initial position to 180 degrees and then back to 0 degrees, depending on how you set the type variable. If the button is held down, the servo will continuously move in the specified direction until released. You may need to adjust the angleStep for different speeds (in video at 02:30).
Video Timestamps
- 00:00 Start
- 00:48 Introduction
- 02:19 Servo motor explained
- 04:00 Wiring explained
- 05:11 Code Explained
- 12:18 Demonstration
Этот учебник является частью: Сервомоторы
- Controlling a Servo with Push Buttons Using Arduino
- Control a Servo Motor with a Push Button: Move Servo in One Direction SPB-2
- Controlling a Servo Motor with a Push Button: Move Servo While Button Is Pressed (SPB-3)
- Controlling a Servo with a Potentiometer Using Arduino
- Controlling a Servo with Potentiometer and LCD1602 using Arduino
- Управление сервомоторами с помощью инфракрасного пульта на Arduino
- Управление сервомотором Arduino с помощью потенциометра
- Управление положением сервопривода с помощью жестов рук для Arduino
- Controlling Two or More Servos with Potentiometers Using an Arduino
- How to Control a 360° Servo with Three Push-Button Switches
- How to Use Continuous 360° Servo with Arduino
- Код Arduino и видео для сервоконтроллера PCA9685 на 16 каналов с разрешением 12 бит V1
- Build an Arduino Servo Toggle Switch with a Push Button
/*
Controlling a servo with Push button with Arduino
this is code #1 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 #1:
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:
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:
*
* 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 (beteen 1 and 179)
int angleStep =10;
const int minAngle = 0;
const int maxAngle = 180;
const int type =2;//watch video for details. Link is at the top of this code (robojax)
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 ");
myservo.write(angle);//initial position
}
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 >= maxAngle) {
angleStep = -angleStep;
if(type ==1)
{
buttonPushed =0;
}
}
if (angle <= minAngle) {
angleStep = -angleStep;
if(type ==2)
{
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
}
}
Вещи, которые могут вам понадобиться
-
АмазонкаСервомотор на Амазон.amzn.to
Ресурсы и ссылки
-
ВнешнийSG90 servosamzn.to
Файлы📁
Другие файлы
-
Технический паспорт мотора SG90 Seroo
robojax-servo-SG90_datasheet.pdf0.12 MB