搜索代码

Build an Arduino Servo Toggle Switch with a Push Button

Build an Arduino Servo Toggle Switch with a Push Button

Build an Arduino Servo Toggle Switch with a Push Button

This project guide will show you how to create a simple yet highly useful circuit: a servo motor that toggles between two positions with each press of a single push button. On the first press, the servo will smoothly sweep from 0 to 180 degrees. On the second press, it will sweep back from 180 to 0 degrees. This is a fundamental concept in robotics and automation, perfect for creating mechanisms like an automatic door latch, a simple robotic arm, a flag waver, or any project that requires a two-state physical action.

We will walk through the required hardware, the wiring, and provide a detailed explanation of the Arduino code that makes it all work.


Hardware and Wiring

The components for this project are minimal and common in most Arduino starter kits. You will need an Arduino board (like an Uno), a standard hobby servo motor (e.g., SG90), a push button, and a few jumper wires.

The wiring is straightforward. The servo's power and ground lines connect to the Arduino's 5V and GND pins, while its signal line connects to a PWM-capable pin (pin 9 in our code). The push button connects between digital pin 2 and GND.

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

The Arduino Code Explained

The sketch uses the standard Servo.h library, which is included with the Arduino IDE. The code is designed to be clean and easy to understand, using flags to keep track of the servo's state and `for` loops to create a smooth sweeping motion.

Global Variables and Configuration

At the top of the code, we define the pins and the servo's behavior. These are the main values you might want to customize for your project.


#include <Servo.h>

// Define variables for servo and button pins
const int servoPin = 9;   // Connect servo signal wire to digital pin 9
const int buttonPin = 2;  // Connect push button to digital pin 2

// Define servo movement parameters
const int initialAngle = 0;   // Servo's starting angle
const int targetAngle1 = 180; // First target angle
const int targetAngle2 = 0;   // Second target angle
const int movingStep = 1;     // Step size for smooth movement (1 degree at a time)

Servo myServo; // Create a Servo object

// State-tracking variables
int currentAngle = initialAngle;
bool buttonPressed = false;
bool servoAt180 = false;
  • servoPin: The pin connected to the servo's signal wire. This must be a PWM pin (marked with a `~` on most Arduino boards).
  • buttonPin: The pin the push button is connected to.
  • initialAngle, targetAngle1, targetAngle2: These define the start and end points of the servo's movement.
  • movingStep: This controls how many degrees the servo moves in each step of the loop. A smaller number creates a smoother, slower motion.

The `setup()` Function

The setup() function runs once when the Arduino is powered on. It initializes the servo, configures the button pin, and sets the servo to its starting position.


void setup() {
  myServo.attach(servoPin); // Attaches the servo to its pin
  pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as input with internal pull-up
  myServo.write(initialAngle);      // Move the servo to its initial position
  Serial.begin(9600);               // Start serial for debugging
}

We use INPUT_PULLUP for the button pin. This activates an internal resistor in the Arduino, which keeps the pin's state HIGH when the button is not pressed. When the button is pressed, it connects the pin to ground, making the state LOW. This useful feature means you don't need to add an external pull-up resistor to your circuit.

The `loop()` - The Core Logic

The main loop continuously checks for a button press. When a press is detected, it moves the servo to its next target position.


void loop() {
  // Read the state of the button
  int buttonState = digitalRead(buttonPin);

  // Check if the button is pressed (LOW) and it wasn't already being held down
  if (buttonState == LOW && !buttonPressed) {
    delay(50); // Debounce delay to prevent multiple triggers
    if (digitalRead(buttonPin) == LOW) { // Re-check the button state
      buttonPressed = true; // Mark the button as pressed

      if (!servoAt180) {
        // If not at 180, move to 180
        for (int angle = currentAngle; angle <= targetAngle1; angle += movingStep) {
          myServo.write(angle);
          delay(15); // Delay between steps to control speed
        }
        currentAngle = targetAngle1;
        servoAt180 = true; // Update state
      } else {
        // If at 180, move back to 0
        for (int angle = currentAngle; angle >= targetAngle2; angle -= movingStep) {
          myServo.write(angle);
          delay(15);
        }
        currentAngle = targetAngle2;
        servoAt180 = false; // Update state
      }
    }
  }

  // Reset the button press flag once the button is released
  if (buttonState == HIGH) {
    buttonPressed = false;
  }
}

The code uses a boolean flag, servoAt180, to remember the servo's last position. When the button is pressed, it checks this flag: if the servo is not at 180 degrees, it moves it there; otherwise, it moves it back to 0. The for loops are what create the smooth sweeping motion, moving the servo one degree at a time with a small delay between each step.


How It Works

Once you upload the code and power on your Arduino, the servo will move to its initial 0-degree position.

  1. First Press: When you press the button, the code detects the input and begins moving the servo from 0 towards 180 degrees, one degree at a time.
  2. Second Press: After the servo has reached 180 degrees, the next button press will cause it to sweep back from 180 towards 0 degrees.

This cycle will repeat with each subsequent button press, creating a reliable and predictable toggle mechanism for your project.

787-Servo with Push button each push moves the servo to final position and stop SPB-180
语言: C++
/*
 * 此代码由robojax.com提供  
 * 您可以在此处查看接线图和本教程的详细信息 https://robojax.com/T661
 */
#include <Servo.h>

 // 为伺服电机和按钮引脚定义变量
const int servoPin = 9; // 将伺服信号线连接到数字引脚9
const int buttonPin = 2; // 将推按钮连接到数字引脚2

 // 定义伺服动作参数
const int initialAngle = 0; // 舵机的起始角度
const int targetAngle1 = 180; // 第一目标角度
const int targetAngle2 = 0; // 第二目标角度(在这种情况下与初始角度相同)
const int movingStep = 1; // 平滑运动的步长(例如,每次 1 度)

Servo myServo; // 创建一个伺服对象

int currentAngle = initialAngle; // 用于跟踪伺服当前角度的变量
bool buttonPressed = false; // 用于跟踪按钮状态的标志
bool servoAt180 = false; // 标志以跟踪舵机是否在180度位置

void setup() {
  myServo.attach(servoPin); // 将伺服电机连接到伺服对象的servoPin上
  pinMode(buttonPin, INPUT_PULLUP); // 将按钮引脚设置为输入,并启用内部上拉电阻
  myServo.write(initialAngle); // 将伺服电机设置为初始角度
  Serial.begin(9600); // 启动串行通信以进行调试
}

void loop() {
 // 读取按钮的状态
  int buttonState = digitalRead(buttonPin);

 // 检查按钮是否被按下(由于INPUT_PULLUP,所以为LOW)且之前没有被按下。
  if (buttonState == LOW && !buttonPressed) {
    delay(50); // 去抖延迟
    if (digitalRead(buttonPin) == LOW) { // 在消抖后确认按钮按下
      buttonPressed = true; // 设置标志以指示按钮当前被按下

      if (!servoAt180) {
 // 将伺服电机移动到180度
        Serial.println("Moving to 180 degrees");
        for (int angle = currentAngle; angle <= targetAngle1; angle += movingStep) {
          myServo.write(angle);
          delay(15); // 调整此延迟以获得所需速度
        }
        currentAngle = targetAngle1;
        servoAt180 = true;
      } else {
 // 将伺服电机移动到0度
        Serial.println("Moving to 0 degrees");
        for (int angle = currentAngle; angle >= targetAngle2; angle -= movingStep) {
          myServo.write(angle);
          delay(15); // 调整此延迟以获得所需速度
        }
        currentAngle = targetAngle2;
        servoAt180 = false;
      }
    }
  }

 // 当按钮释放时重置按钮被按下的标志
  if (buttonState == HIGH) {
    buttonPressed = false;
  }
}

资源与参考

尚无可用资源。

文件📁

没有可用的文件。