# 9.Servo control

## 9.1. Overview
 In this section, you will learn how to drive the servo to achieve 0~180° rotation.
 
## 9.2 Working principle

### 9.2.1. Steering gear

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/9.lesson_servo.png" width="150" height="150"/>
 
 The steering gear ( servo motor ) control pulse signal period is a 20MS pulse width modulation signal (PWM), the pulse
 width is from 0.5ms to 2.5ms, and the corresponding steering position changes linearly from 0 to 180 degrees.
 There is a reference circuit inside the steering gear, which generates a pulse signal with a period of 20ms and a width of
 1.5ms. There is a comparator that compares the external signal with the reference signal to determine the direction and size,
 thereby generating a motor rotation signal.

## 9.3 Connection lines

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/9.lession_connect_line.png" width="800" height="600"/>
 
## 9.4 Upload code program

### 9.4.1 Connect the main control SD board to the computer using a USB cable

<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>

### 9.4.2 Open the program file (path: 2_ESP32_S3_PLUS\Lesson_9_Steering_gear_control)
 Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
 in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
 upload to be completed .
 
## 9.5 Code analysis
 
 Declare the servo library Servo, define the servo pin A0 and instantiate the servo object myServo.

```cpp
#include <ESP32Servo.h>

#define SERVO_PIN 9  // Connect the servo signal line to A0 of UNOR4 MINIMA
Servo myServo;        // Instantiate a steering gear object
```

 Set the servo pin to output mode and initialize the servo.
 
```cpp

void setup() {
  pinMode(SERVO_PIN, OUTPUT);  // Set the servo connected pin to output mode
  myServo.attach(SERVO_PIN);   // Set the steering gear object
}
```

Let the servo rotate back and forth between 0~180° in the loop function.

```cpp

void loop() {
  // Let the steering gear turn from 180 to 0 degrees
  for (int angle = 180; angle >= 0; angle--) {
    myServo.write(angle);
    delay(10);
  }

  // Let the steering gear turn from 0 to 180 degrees
  for (int angle = 0; angle <= 180; angle++) {
    myServo.write(angle);
    delay(10);
  }
}
```