Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

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.

Components Required

../_images/list_2.12.png

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.

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