2.12 Servo

Overview

In this lesson, you will learn something about Servo. Servo is a kind of driver whose position (angular) can be adjustable and kept or a rotary actuator that allows for precise control of angular position. Currently, it is widely used in upscale remote control toys, such as airplane, submarine, telerobot and so on.

Fritzing Circuit

In this example, we use PWM pin 9 to drive the Servo, and get the orange wire of the servo connected to the PWM pin 9, the red one to 5V, and the brown one to GND.

../_images/image454.png

Schematic Diagram

../_images/image455.png

Code

Note

  • You can open the file 2.12_servo.ino under the path of sunfounder_vincent_kit_for_arduino\code\2.12_servo directly.

  • Or copy this code into Arduino IDE 1/2.

  • Or click Open Code to open it in Web Editor.

  • Then Upload the Code to the board.

Once you finish uploading the codes to the Mega2560 board, you can see the servo arm rotating in the range 0°~180°.

Code Analysis

By calling the library Servo.h, you can drive the servo easily.

#include <Servo.h>

Library Functions:

Servo

Create Servo object to control a servo.

uint8_t attach(int pin);

Turn a pin into a servo driver. Calls pinMode. Returns 0 on failure.

void detach();

Release a pin from servo driving.

void write(int value);

Set the angle of the servo in degrees, 0 to 180.

int read();

Return that value set with the last write().

bool attached();

Return 1 if the servo is currently attached.

Phenomenon Picture

../_images/image132.jpeg