# 서보 모터 제어

## 서보 모터 제어

이 문서에서는 서보(Servo) 모터 제어에 대해서 다룬다.

### 결선도

![](/files/-Mf5U45ru1_TaxY0hcPN)

### 샘플 코드

```cpp
#include <Servo.h>

const int SERVO = 10;
Servo servo;

void setup()
{
  servo.attach(SERVO);
  servo.write(0);

  delay(1000);

  for (int cnt = 1; cnt <= 3; cnt++) {
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(1000);
  }

  servo.detach();
}

void loop()
{

}
```

### 컴파일

`Ctrl+R` 또는 스케치 메뉴의 `확인/컴파일`을 눌러 컴파일을 진행한다.

### 업로드

`Ctrl+U` 또는 스케치 메뉴의 `업로드`를 눌러 업로드를 진행한다.

### 실행 결과

서보 모터가 3회 움직이는 것을 확인할 수 있다.

### 코드 설명

서보 모터를 사용하기 위해서는 해당 기능이 포함된 헤더 파일인 `Servo.h`를 불러와야 한다.

```cpp
#include <Servo.h>
```

또한 서보모터를 제어하기 위해서 `Servo` 형태의 변수를 선언해야 한다.

```cpp
Servo servo;
```

서보모터의 제어를 위한 핀 번호를 10번으로 설정한다.

```cpp
const int SERVO = 10;
```

최초 1회만 작동하기 위해서 `loop` 함수 대신 `setup` 함수에 코드를 작성한다.

서보모터를 미리 설정해둔 핀 번호에 연결한다.

```cpp
servo.attach(SERVO);
```

서보모터의 출력각도를 0도로 설정한다.

```cpp
servo.write(0);
```

1초 딜레이를 부여한다.

```cpp
delay(1000);
```

서보모터를 0도와 180도로 번갈아 1초간격으로 3회 설정한다.

```cpp
for (int cnt = 1; cnt <= 3; cnt++) {
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(1000);
}
```

서보모터의 연결을 해제한다.

```cpp
servo.detach();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sysout.co.kr/base-language/arduino/arduino-control/servo-motor-control.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
