Search Code

쉬운 아두이노 프로젝트: 푸시버튼으로 서보 모터를 180도에서 0도로, 그리고 다시 돌아가게 제어하기

쉬운 아두이노 프로젝트: 푸시버튼으로 서보 모터를 180도에서 0도로, 그리고 다시 돌아가게 제어하기

소개

이 문서는 푸시버튼을 사용하여 서보 모터를 제어하는 간단한 Arduino 프로젝트를 설명합니다. 서보 모터는 특정 위치로 회전할 수 있는 정밀한 모터로, 로봇 공학 및 자동화와 같은 응용 분야에 이상적입니다. 이 프로젝트는 버튼을 누르면 서보가 0도에서 180도로 움직이고, 버튼을 놓으면 0도로 돌아가도록 합니다.

프로젝트 구성 요소 및 배선

Arduino 보드, 서보 모터, 푸시버튼이 필요합니다.

배선 지침:

  • 서보 모터: 신호선(보통 노란색/주황색)을 Arduino 3번 핀에, 전원선(빨간색)을 5V에, 접지선(검은색/갈색)을 GND에 연결합니다.
  • 푸시버튼: 한쪽 다리를 디지털 2번 핀에, 다른 쪽 다리를 GND 핀에 연결합니다. 끝입니다! Arduino의 내부 풀업 저항을 사용하므로 외부 저항이 필요하지 않습니다.

 

코드 설명

프로그램은 핀 정의, setup() 함수, loop() 함수의 세 가지 주요 부분으로 나뉩니다.

핀 정의

이 섹션에서는 필요한 라이브러리를 설정하고 사용 중인 핀에 의미 있는 이름을 지정합니다.

#include <Servo.h>

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

Servo myServo;

setup() 함수

setup() 함수에는 Arduino 보드에 전원이 켜지거나 재설정될 때 한 번만 실행되는 코드가 포함됩니다. 초기 구성을 위해 사용됩니다.

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

핵심적인 변경 사항은 pinMode(buttonPin, INPUT_PULLUP);입니다. 이는 핀의 전압을 HIGH로 끌어올리는 내부 저항을 활성화합니다. 버튼을 누르면 핀이 접지에 연결되어 전압이 LOW로 떨어집니다.

loop() 함수

loop() 함수에는 주요 프로그램 로직이 포함되어 있으며 setup() 함수가 완료된 후 반복적으로 영원히 실행됩니다.

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

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

여기서 로직은 이제 반대입니다. 버튼을 누르면 LOW 신호가 발생하므로 if (buttonState == LOW) 조건을 사용하여 서보를 180도로 움직입니다.

이미지

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++
#include <Servo.h>
/*
This is sketch for controlling servo motor. when push button is pressed, the servo moves to 180 degreees and stays there. when the push button is released, the servo motor returns back to 0 degree.
*/
// Define the pin for the servo motor
const int servoPin = 3;
// Define the pin for the push button
const int buttonPin = 2;

// Create a Servo object
Servo myServo;

void setup() {
  // Attach the Servo object to the servo pin
  myServo.attach(servoPin);
  // Set the button pin as an input
  pinMode(buttonPin, INPUT);
  // Start the servo at 0 degrees
  myServo.write(0);
}

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

  // If the button is pressed (HIGH)
  if (buttonState == HIGH) {
    // Move the servo to 180 degrees
    myServo.write(180);
  } else {
    // If the button is released (LOW), move the servo back to 0 degrees
    myServo.write(0);
  }
}

필요할 수 있는 것들

자원 및 참고자료

아직 자원이 없습니다.

파일📁

파일이 없습니다.