Easy Arduino Project: Control a Servo with a Pushbutton 180 degree to 0 and back

Easy Arduino Project: Control a Servo with a Pushbutton 180 degree to 0 and back

Introduction

This article explains a simple Arduino project that uses a pushbutton to control a servo motor. A servo motor is a precise motor that can rotate to a specific position, making it ideal for applications like robotics and automation. This project will make a servo move from 0 to 180 degrees when a button is pressed and return to 0 when released.

Project Components and Wiring

You will need an Arduino board, a servo motor, and a pushbutton.

Wiring Instructions:

  • Servo Motor: Connect the signal wire (usually yellow/orange) to Arduino pin 3, the power wire (red) to 5V, and the ground wire (black/brown) to GND.
  • Pushbutton: Connect one leg to digital pin 2 and the other leg to a GND pin. That's it! By using the Arduino's internal pull-up resistor, you do not need an external resistor.

 

The Code Explained

The program is broken down into three main parts: the pin definitions, the setup() function, and the loop() function.

Pin Definitions

This section sets up the required libraries and assigns meaningful names to the pins you're using.

#include <Servo.h>

const int servoPin = 3;
const int buttonPin = 2;

Servo myServo;

The setup() Function

The setup() function contains code that runs only once when the Arduino board is powered on or reset. It's used for initial configuration.

void setup() {
  myServo.attach(servoPin);
  pinMode(buttonPin, INPUT_PULLUP);
  myServo.write(0);
}

The crucial change is pinMode(buttonPin, INPUT_PULLUP);. This activates an internal resistor that pulls the pin's voltage to HIGH. When you press the button, it connects the pin to ground, and the voltage drops to LOW.

The loop() Function

The loop() function contains the main program logic and runs repeatedly forever after the setup() function is finished.

void loop() {
  int buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    myServo.write(180);
  } else {
    myServo.write(0);
  }
}

The logic here is now reversed. Since the button press results in a LOW signal, the if (buttonState == LOW) condition is used to move the servo to 180 degrees.

تصاویر

Arduino wiring for Servo motor with a push button
Arduino wiring for Servo motor with a push button
795-Ardunino code to control servo motor using a push button to move between 180 and zero degree
زبان: C++
کپی شد!

مواردی که ممکن است به آن‌ها نیاز داشته باشید

منابع و مراجع

هنوز هیچ منبعی موجود نیست.

فایل‌ها📁

هیچ فایلی موجود نیست.