Código de Pesquisa

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
Idioma: C++
/*
 * Este código é fornecido por robojax.com Você pode visualizar o diagrama de fiação e os detalhes deste tutorial aqui https://robojax.com/T661
 */
#include <Servo.h>

 // Defina variáveis para os pinos do servo e do botão.
const int servoPin = 9; // Conecte o fio de sinal do servo ao pino digital 9.
const int buttonPin = 2; // Conecte o botão de pressão ao pino digital 2.

 // Defina os parâmetros de movimento do servo
const int initialAngle = 0; // Ângulo inicial do servo
const int targetAngle1 = 180; // Primeiro ângulo alvo
const int targetAngle2 = 0; // Ângulo alvo secundário (o mesmo que o inicial neste caso)
const int movingStep = 1; // Tamanho do passo para movimento suave (por exemplo, 1 grau de cada vez)

Servo myServo; // Crie um objeto Servo

int currentAngle = initialAngle; // Variável para acompanhar o ângulo atual do servo.
bool buttonPressed = false; // Sinal para rastrear o estado do botão
bool servoAt180 = false; // Flag para rastrear se o servo está a 180 graus

void setup() {
  myServo.attach(servoPin); // Anexa o servo no servoPin ao objeto servo.
  pinMode(buttonPin, INPUT_PULLUP); // Defina o pino do botão como entrada com resistor de pull-up interno.
  myServo.write(initialAngle); // Defina o servo para seu ângulo inicial.
  Serial.begin(9600); // Inicie a comunicação serial para depuração
}

void loop() {
 // Leia o estado do botão
  int buttonState = digitalRead(buttonPin);

 // Verifique se o botão está pressionado (BAIXO por causa do INPUT_PULLUP) e que não foi pressionado antes.
  if (buttonState == LOW && !buttonPressed) {
    delay(50); // Atraso de debounce
    if (digitalRead(buttonPin) == LOW) { // Confirme a pressão do botão após o debounce.
      buttonPressed = true; // Defina a bandeira para indicar que o botão está atualmente pressionado.

      if (!servoAt180) {
 // Mover o servomotor para 180 graus
        Serial.println("Moving to 180 degrees");
        for (int angle = currentAngle; angle <= targetAngle1; angle += movingStep) {
          myServo.write(angle);
          delay(15); // Ajuste esse atraso para a velocidade desejada.
        }
        currentAngle = targetAngle1;
        servoAt180 = true;
      } else {
 // Movimente o servo para 0 graus.
        Serial.println("Moving to 0 degrees");
        for (int angle = currentAngle; angle >= targetAngle2; angle -= movingStep) {
          myServo.write(angle);
          delay(15); // Ajuste esse atraso para a velocidade desejada.
        }
        currentAngle = targetAngle2;
        servoAt180 = false;
      }
    }
  }

 // Reiniciar a bandeira buttonPressed quando o botão é solto
  if (buttonState == HIGH) {
    buttonPressed = false;
  }
}

Recursos e referências

Ainda não há recursos.

Arquivos📁

Nenhum arquivo disponível.