Chuyển tới nội dung
Home » Arduino Uno Servo Motor | How Do Servo Motors Work?

Arduino Uno Servo Motor | How Do Servo Motors Work?

How to Control a Servo With an Arduino

Step 3: How It Works

Servos are clever devices. Using just one input pin, they receive the position from the Arduino and they go there. Internally, they have a motor driver and a feedback circuit that makes sure that the servo arm reaches the desired position. But what kind of signal do they receive on the input pin?

It is a square wave similar to PWM. Each cycle in the signal lasts for 20 milliseconds and for most of the time, the value is LOW. At the beginning of each cycle, the signal is HIGH for a time between 1 and 2 milliseconds. At 1 millisecond it represents 0 degrees and at 2 milliseconds it represents 180 degrees. In between, it represents the value from 0–180. This is a very good and reliable method. The graphic makes it a little easier to understand.

Remember that using the Servo library automatically disables PWM functionality on PWM pins 9 and 10 on the Arduino UNO and similar boards.

Code breakdown

The code simply declares the servo object and then initializes the servo by using the servo.attach() function. We shouldn’t forget to include the servo library. In the loop(), we set the servo to 0 degrees, wait, then set it to 90, and later to 180 degrees.

Testing it out

After we have successfully uploaded the code to the board, the standard servo should now start moving from 0 – 180, and then start moving from 180 – 0. This is due to the two for loops in the program, which gradually increases the

variable, which is written to the servo.

pos

Congratulations! That was just a few easy steps to get started with standard servo motors. Now that you have this working, you can start exploring a lot of different cool projects that uses servo motors, and perhaps start making your very own robot!

How to Control a Servo With an Arduino
How to Control a Servo With an Arduino

Step 4: More Things About Servos

Controlling servos is easy, and here are a few more tricks we can use:

Controlling the exact pulse time

Arduino has a built-in function servo.write(degrees) that simplifies the control of servos. However, not all servos respect the same timings for all positions. Usually, 1 millisecond means 0 degrees, 1.5 milliseconds mean 90 degrees, and, of course, 2 milliseconds mean 180 degrees. Some servos have smaller or larger ranges.

For better control, we can use the servo.writeMicroseconds(us) function, which takes the exact number of microseconds as a parameter. Remember, 1 millisecond equals 1,000 microseconds.

More servos

In order to use more than one servo, we need to declare multiple servo objects, attach different pins to each one, and address each servo individually. First, we need to declare the servo objects—as many as we need:

// Create servo objects Servo Servo1, Servo2, Servo3;

Then we need to attach each object to one servo motor. Remember, every servo motor uses an individual pin:

Servo1.attach(servoPin1); Servo2.attach(servoPin2); Servo3.attach(servoPin3);

In the end, we just have to address each servo object individually:

Servo1.write(0); // Set Servo 1 to 0 degrees Servo2.write(90); // Set Servo 2 to 90 degrees

Connection-wise, the grounds from the servos go to GND on the Arduino, the servo power to 5V or VIN (depending on the power input), and in the end, each signal line has to be connected to a different digital pin. Contrary to popular belief, servos don’t need to be controlled by PWM pins—any digital pin will work.

Continuous rotation servos

There is a special breed of servos labelled as continuous rotation servos. While a normal servo goes to a specific position depending on the input signal, a continuous rotation servo either rotates clockwise or counter-clockwise at a speed proportional to the signal. For example, the Servo1.write(0) function will make the servomotor spin counter-clockwise at full speed. The Servo1.write(90) function will stop the motor and Servo1.write(180) will turn the motor clockwise at full speed.

There are multiple uses for such servos; however, they are really slow. If you are building a microwave and need a motor to turn the food, this is your choice. But be careful, microwaves are dangerous!

How Do Servo Motors Work?

You can control the servo motor by sending a series of pulses to it. A typical servo motor expects a pulse every 20 milliseconds (i.e., the signal should be 50Hz).

The length of the pulse determines the position of the servo motor.

  • A short pulse of 1 ms or less will rotate the servo to 0 degrees (one extreme).
  • A pulse duration of 1.5 ms will rotate the servo to 90 degrees (middle position).
  • A pulse duration of 2 ms or so will rotate the servo to 180 degrees (other extreme).

Pulses ranging from 1ms to 2ms will rotate the servo to a position proportional to the pulse width. The animation below will help you understand the relationship between pulses and position.

It is important to note that there is no standard for the exact relationship between pulses and position, so you may need to tweak your sketch to adjust for the range of your servo.

Also, the pulse duration can vary between brands; for example, it might be 2.5ms for 180 degrees and 0.5ms for 0 degrees.

Arduino tutorial 7- How to control Servo motor with Arduino (code explained) | using servo library
Arduino tutorial 7- How to control Servo motor with Arduino (code explained) | using servo library

Popular RC / Hobby Servos for Arduino Projects

There are many different models and manufacturers of RC or hobby. The main consideration when choosing a servo motor is its torque, operating voltage, current draw and size.

Here are the two most popular servo models among makers, the SG90 Micro Servo and the MG996R.

SG90 Micro Servo technical specifications:

Stall Torque 1.2kg·cm @4.8V, 1.6kg·cm @6V,
Operating Voltage 3.5 – 6V
No Load Current 100mA
Stall Current 650mA
Max Speed 60 degrees in 0.12s
Weight 9g

MG996R Servo technical specifications:

Stall Torque 11kg.cm @4.8v, 13kg.cm @6V
Operating Voltage 4.8 – 7.2V
No Load Current 220mA @4.8V, 250mA @6V
Stall Current 650mA
Max Speed 60 degrees in 0.20s
Weight 55g

Servo Motor Basics with Arduino

Learn how to connect and control servo motors with your Arduino board.

The Servo Library is a great library for controlling servo motors. In this article, you will find two easy examples that can be used by any Arduino board.

The first example controls the position of an RC (hobby) servo motor with your Arduino and a potentiometer. The second example sweeps the shaft of an RC servo motor back and forth across 180 degrees.

You can also visit the Servo GitHub repository to learn more about this library.

Arduino UNO Tutorial #3 - Servo Motor Project (Set Up)
Arduino UNO Tutorial #3 – Servo Motor Project (Set Up)

Servo Motor Pinout

Servo motors typically have three connections, as outlined below.

GND serves as a common ground for the motor and the logic.

5V is a positive voltage that powers the servo.

Control is an input for the control system.

The color of the wires varies between servo motors, but the red wire is always 5V and GND is either black or brown. The control wire is usually orange or yellow.

Introduction: Arduino Servo Motors

Servo motors are great devices that can turn to a specified position.

Usually, they have a servo arm that can turn 180 degrees. Using the Arduino, we can tell a servo to go to a specified position and it will go there. As simple as that!

Servo motors were first used in the Remote Control (RC) world, usually to control the steering of RC cars or the flaps on a RC plane. With time, they found their uses in robotics, automation, and of course, the Arduino world.

Here we will see how to connect a servo motor and then how to turn it to different positions.

The first motor I ever connected to an Arduino, seven years ago, was a Servo motor. Nostalgic moment over, back to work!

We will need the following things:

  1. An Arduino board connected to a computer via USB
  2. A servo motor
  3. Jumper wires

There are few big names in the servo motor world. Hitec and Futaba are the leading RC servo manufacturers. Good places to buy them are Servocity, Sparkfun, and Hobbyking.

This instructable and many more can be found in my Arduino Development Cookbook available here. 😀

servo motor experiment | servo motor arduino | servo motor arduino potentiometer | SG90  Servo, MG90
servo motor experiment | servo motor arduino | servo motor arduino potentiometer | SG90 Servo, MG90

Bài viết liên quan

  • Bài 9: Cảm biến ánh sáng (Quang trở) cách chia điện áp trong môi trường Arduino
  • Bài 8: Cảm biến góc nghiêng sử dụng ngắt (INTERRUPT) trong môi trường Arduino
  • Bài 7: Cảnh báo nhiệt độ (LM35) bằng còi báo sử dụng Arduino Uno
  • Bài 6: Tạo âm thanh (Còi) bằng Arduino
  • Bài 5: Thay đổi màu sắc Led RGB sử dụng Arduino
  • Bài 4: PWM | Thay đổi ánh sáng của LED trên Arduino
  • Bài 3: Sử dụng Arduino làm hệ thống đèn giao thông
  • Bài 2: Chớp tắt LED trên Arduino Uno (Phần 2)
  • Bài 1: Chớp tắt LED trên Arduino Uno

In this tutorial we will learn how servo motors work and how to control servo motors with Arduino. Servo motors are very popular and widely used in many Arduino projects because they are easy to use and provide great position control.

Servos are great choice for robotics projects, automation, RC models and so on. I have already used them in many of my Arduino projects and you can check out some of them here:

  • DIY Arduino Robot Arm with Smartphone Control
  • Arduino Ant Hexapod Robot
  • DIY Arduino based RC Hovercraft
  • SCARA Robot | How To Build Your Own Arduino Based Robot
  • DIY Mars Perseverance Rover Replica – Arduino based Project

You can watch the following video or read the written tutorial below. It includes several examples how to use a servo motor with Arduino, wiring diagram and codes. In additional, it has a guide how to control multiple servo motors with Arduino using the PCA9685 PWM driver.

Step 2: Code

The following code will turn a servo motor to 0 degrees, wait 1 second, then turn it to 90, wait one more second, turn it to 180, and then go back.

// Include the Servo library#include

// Declare the Servo pin int servoPin = 3; // Create a servo object Servo Servo1; void setup() { // We need to attach the servo to the used pin number Servo1.attach(servoPin); } void loop(){ // Make servo go to 0 degrees Servo1.write(0); delay(1000); // Make servo go to 90 degrees Servo1.write(90); delay(1000); // Make servo go to 180 degrees Servo1.write(180); delay(1000); }

If the servo motor is connected on another digital pin, simply change the value of servoPin to the value of the digital pin that has been used.

Attachments

Using Servo Motors with Arduino
Using Servo Motors with Arduino

Programming the board

To program the board, you will need to have installed the offline editor, or use the online editor. There’s no need to install any external libraries.

Before we begin, let’s take a look at some of the core functions in the program:

  • – includes the Servo library.


    #include

  • – create a servo object.


    Servo myservo

  • – attach the servo to a pin.


    myservo.attach(9)

  • – write a value to the servo (0-180).


    myservo.write(pos)

The code can be found by navigating to File > Examples > Servo > Sweep, or can be copied directly from below. Upload the program to the board.

1#include

23Servo myservo; // create servo object to control a servo4// twelve servo objects can be created on most boards56int pos = 0; // variable to store the servo position78void setup() {9 myservo.attach(9); // attaches the servo on pin 9 to the servo object10}1112void loop() {13 for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees14 // in steps of 1 degree15 myservo.write(pos); // tell servo to go to position in variable ‘pos’16 delay(15); // waits 15ms for the servo to reach the position17 }18 for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees19 myservo.write(pos); // tell servo to go to position in variable ‘pos’20 delay(15); // waits 15ms for the servo to reach the position21 }22}

Code:

#include

Servo myservo; int pos = 0; void setup() { myservo.attach(9); } void loop() { for(pos = 0; pos < 180; pos += 1){ myservo.write(pos); delay(15); } for(pos = 180; pos>=1; pos-=1) { myservo.write(pos); delay(15); } }

Gải thích code

#include

#include

Cho phép chương trình của bạn tải một thư viện đã được viết sẵn. Tức là bạn có thể truy xuất được những tài nguyên trong thư viện này từ chương trình của mình.

Servo myservo;

Khởi tạo đối tượng Servo và đặt tên là myservo.

Hàm attach()

Nếu các bạn theo dõi từ những bài trước và đã quen thuộc với hàm

pinMode()

thì hàm

attach()

ở đây cũng tương tự, dùng để khai báo chân kết nối.

Cú pháp

myservo.attach(pin);

Trong bài viết này mình dùng Pin D9 để điều khiển động cơ Servo. Các bạn có thể thay thế các chân Digital/Analog khác có trên Board mạch.

myservo.write(pos);

Dùng để ghi các dữ liệu ra và ở đây là xuất tọa độ ra cho servo.

Using Servo Motor SG90 with Arduino
Using Servo Motor SG90 with Arduino

Examples

Knob

Controlling a servo position using a potentiometer (variable resistor).

1#include

23Servo myservo; // create servo object to control a servo45int potpin = 0; // analog pin used to connect the potentiometer6int val; // variable to read the value from the analog pin78void setup() {9 myservo.attach(9); // attaches the servo on pin 9 to the servo object10}1112void loop() {13 val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)14 val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)15 myservo.write(val); // sets the servo position according to the scaled value16 delay(15); // waits for the servo to get there17}

Sweep

Sweeps the shaft of a RC servo motor back and forth across 180 degrees.

1#include

23Servo myservo; // create servo object to control a servo4// twelve servo objects can be created on most boards56int pos = 0; // variable to store the servo position78void setup() {9 myservo.attach(9); // attaches the servo on pin 9 to the servo object10}1112void loop() {13 for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees14 // in steps of 1 degree15 myservo.write(pos); // tell servo to go to position in variable ‘pos’16 delay(15); // waits 15ms for the servo to reach the position17 }18 for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees19 myservo.write(pos); // tell servo to go to position in variable ‘pos’20 delay(15); // waits 15ms for the servo to reach the position21 }22}

Suggested changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.

Basic servo control

In this tutorial, we will learn how to control a standard servo motor, to go back and forth across 180 degrees, using a `for loop()`. This is done with the help of the Servo library, which is pre-installed library in the Arduino IDE (both offline and online versions).

In this tutorial, we will learn how to control a standard servo motor, to go back and forth across 180 degrees, using a

. This is done with the help of the Servo library, which is pre-installed library in the Arduino IDE (both offline and online versions).

for loop()

Note: This tutorial uses an Arduino UNO, but you can use any official Arduino board.

Step 1: How to Connect Them

A servo motor has everything built in: a motor, a feedback circuit, and most important, a motor driver. It just needs one power line, one ground, and one control pin.

Following are the steps to connect a servo motor to the Arduino:

  1. The servo motor has a female connector with three pins. The darkest or even black one is usually the ground. Connect this to the Arduino GND.
  2. Connect the power cable that in all standards should be red to 5V on the Arduino.
  3. Connect the remaining line on the servo connector to a digital pin on the Arduino.

Check the image for a view of the servo connected to the Arduino.

Servo Motors, how do they work?
Servo Motors, how do they work?

Standard servo motors

Standard servo motors are actuators that allow for precise control of position (angle). A typical characteristic is that the angle of the motor is 0 – 180 degrees. With other words, it can make one half of a rotation.

A standard servo motor, just as other motors, are essentially just a DC motor, but with some extra features:

  • Control circuit for controlling the motor, e.g. setting the angle.
  • Gears that transform speed into torque, which makes it capable of doing “heavy lifting” at a slower speed, as opposed to a regular DC motor that just spins very fast!
  • Potentiometer that keeps track of its angle. This makes it possible for the servo to “know where it is”.

Take a look at the image below to see how a Servo looks like inside:

The different wires

Almost all servos come with a set of 3 wires. These are PWR, GND and Signal. For a very simple circuit, all that is needed is to connect each of these two pins on the Arduino:

  • PWR (RED) – connects to 5V on the Arduino.
  • GND (BLACK) – connects to GND on the Arduino.
  • Signal (WHITE) – connects to a digital pin on the Arduino (typically 9).

Note: The color combination varies from servo to servo, but typically the red and black remains.

Note: Depending on what Arduino you are using, the signal pin may vary.

What is Servo Motor?

A servo motor is a closed-loop system that uses position feedback to control its motion and final position. There are many types of servo motors and their main feature is the ability to precisely control the position of their shaft.

In industrial type servo motors the position feedback sensor is usually a high precision encoder, while in the smaller RC or hobby servos the position sensor is usually a simple potentiometer. The actual position captured by these devices is fed back to the error detector where it is compared to the target position. Then according to the error the controller corrects the actual position of the motor to match with the target position.

In this tutorial we will take a detailed look at the hobby servo motors. We will explain how these servos work and how to control them using Arduino.

Hobby servos are small in size actuators used for controlling RC toys cars, boats, airplanes etc. They are also used by engineering students for prototyping in robotics, creating robotic arms, biologically inspired robots, humanoid robots and so on.

16 channel servo controller with Arduino | PCA9685 16 channel PWM servo motor driver tutorial
16 channel servo controller with Arduino | PCA9685 16 channel PWM servo motor driver tutorial

Step 2: Code

The following code will turn a servo motor to 0 degrees, wait 1 second, then turn it to 90, wait one more second, turn it to 180, and then go back.

// Include the Servo library#include

// Declare the Servo pin int servoPin = 3; // Create a servo object Servo Servo1; void setup() { // We need to attach the servo to the used pin number Servo1.attach(servoPin); } void loop(){ // Make servo go to 0 degrees Servo1.write(0); delay(1000); // Make servo go to 90 degrees Servo1.write(90); delay(1000); // Make servo go to 180 degrees Servo1.write(180); delay(1000); }

If the servo motor is connected on another digital pin, simply change the value of servoPin to the value of the digital pin that has been used.

Attachments

Conclusion

So, we have covered almost everything we need to know about using servo motors with Arduino. Of course, there are some many manufacturers and models of these type of hobby or RC servo motors, and each of them has its own unique features that might differ from what we explained above.

The possibilities for creating awesome robotics, automation and RC projects using motors are endless, however choosing the right model for your application is very important.

I hope you enjoyed this tutorial and learned something new. Feel free to ask any question in the comments section below, as well as make sure you can my Arduino Projects Collection.

How to control Servo motor with proximity sensor with Arduino Uno
How to control Servo motor with proximity sensor with Arduino Uno

Introduction: Arduino Servo Motors

Servo motors are great devices that can turn to a specified position.

Usually, they have a servo arm that can turn 180 degrees. Using the Arduino, we can tell a servo to go to a specified position and it will go there. As simple as that!

Servo motors were first used in the Remote Control (RC) world, usually to control the steering of RC cars or the flaps on a RC plane. With time, they found their uses in robotics, automation, and of course, the Arduino world.

Here we will see how to connect a servo motor and then how to turn it to different positions.

The first motor I ever connected to an Arduino, seven years ago, was a Servo motor. Nostalgic moment over, back to work!

We will need the following things:

  1. An Arduino board connected to a computer via USB
  2. A servo motor
  3. Jumper wires

There are few big names in the servo motor world. Hitec and Futaba are the leading RC servo manufacturers. Good places to buy them are Servocity, Sparkfun, and Hobbyking.

This instructable and many more can be found in my Arduino Development Cookbook available here. 😀

Frequently Asked Questions (FAQs)

Using a servo motor with Arduino is quite easy. The servo motor has just 3 wires, two of which are GND and 5V for powering, and the third wire is the control line which goes to the Arduino board.

We can run servo motors directly from Arduino, but we might have power problems. If the servo motor draws more than 500mA of current, the Arduino board might lose it’s power and reset. It’s better to always use a separate power source for the servo motors.

Using the Arduino Servo library we can control up to 12 servo motors with most Arduino boards, and up to 48 servo motors with the Arduino Mega board. Of course, we need to use a dedicated power source for the servo motors.

Servo Motor Basics with Arduino

Learn how to connect and control servo motors with your Arduino board.

The Servo Library is a great library for controlling servo motors. In this article, you will find two easy examples that can be used by any Arduino board.

The first example controls the position of an RC (hobby) servo motor with your Arduino and a potentiometer. The second example sweeps the shaft of an RC servo motor back and forth across 180 degrees.

You can also visit the Servo GitHub repository to learn more about this library.

AC servo controlled with Arduino
AC servo controlled with Arduino

Arduino and PCA9685 PWM/ Servo Driver

There’s also another way of controlling servos with Arduino, and that’s using the PCA9685 servo driver. This is a 16-Channel 12-bit PWM and servo driver which communicates with Arduino using the I2C bus. It has a built in clock so it can drive 16 servos free running, or independently of Arduino.

What’s even cooler we can daisy-chain up to 62 of these drivers on a single I2C bus. So theoretically we can control up to 992 servos using only the two I2C pins from the Arduino board. The 6 address select pins are used for setting different I2C addressed for each additional driver. We just need to connect the solder pads according to this table.

Here’s the circuit schematic and we can once again notice that we need a separate power supply for the servos.

You can get the components needed for this example from the links below:

  • MG996R Servo Motor …………………………. Amazon / Banggood / AliExpress
  • PCA9685 PWM Servo Driver ………………. Amazon / Banggood / AliExpress
  • Arduino Board ……………………………………. Amazon / Banggood / AliExpress
  • 5V 6A DC Power Supply …………………..….. Amazon / Banggood / AliExpress

Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.

Now let’s take a look at the Arduino code. For controlling this servo driver we will use the PCA9685 library which can be downloaded from GitHub.

Arduino and PCA9685 Code


/* Servo Motor Control using Arduino and PCA9685 Driver by Dejan, https://howtomechatronics.com Library: https://github.com/NachtRaveVL/PCA9685-Arduino */ PCA9685 driver; // PCA9685 outputs = 12-bit = 4096 steps // 2.5% of 20ms = 0.5ms ; 12.5% of 20ms = 2.5ms // 2.5% of 4096 = 102 steps; 12.5% of 4096 = 512 steps PCA9685_ServoEvaluator pwmServo(102, 470); // (-90deg, +90deg) // Second Servo // PCA9685_ServoEvaluator pwmServo2(102, 310, 505); // (0deg, 90deg, 180deg) void setup() { Wire.begin(); // Wire must be started first Wire.setClock(400000); // Supported baud rates are 100kHz, 400kHz, and 1000kHz driver.resetDevices(); // Software resets all PCA9685 devices on Wire line driver.init(B000000); // Address pins A5-A0 set to B000000 driver.setPWMFrequency(50); // Set frequency to 50Hz } void loop() { driver.setChannelPWM(0, pwmServo.pwmForAngle(-90)); delay(1000); driver.setChannelPWM(0, pwmServo.pwmForAngle(0)); delay(1000); driver.setChannelPWM(0, pwmServo.pwmForAngle(90)); delay(1000); }

Code language: Arduino (arduino)

So first we need to include the libraries and define the PCA9685 object. Then using the Servo_Evaluator instance define the pulses duration or the PWM output of the driver. Note that the outputs are 12-bit, or that’s a resolution of 4096 steps. So the minimum pulse duration of 0.5ms or 0 degrees position would correspond to 102 steps, and the maximum pulse duration of 2.5ms or 180 degrees position to 512 steps. But as explained earlier these values should be adjusted according your servo motor. I had value from 102 to 470 which corresponded to 0 to 180 degrees position.

In the setup section we need to define the I2C clock rate, set the driver address and set the frequency to 50Hz.

In the loop section, using the setChannelPWM() and pwmForAngle() functions we simply set the servo to the desired angle.

I connected a second servo to the driver, and as I expected, it wasn’t positioning the same as the first one, and that’s because the servos that I’m using are cheap copies and they are not so reliable. However, this isn’t a big problem because using the Servo_Evaluator instance we can set different output settings for each servo. We can also adjust the 90 degrees position in case it’s not precisely in the middle. In that way all servos will work the same and position at the exact angle.

Controlling a lot of servos with Arduino and the PCA9685 drivers

We will take a look at one more example and that’s controlling a lot of servos with multiple chained PCA9685 drivers.

For that purpose we need to connect the drivers to each other and connect the appropriate address select solder pads. Here’s the circuit schematic:

Let’s take a look at the Arduino code now.


/* Servo Motor Control using Arduino and PCA9685 Driver by Dejan, https://howtomechatronics.com Library: https://github.com/NachtRaveVL/PCA9685-Arduino */ PCA9685 driver; // PCA9685 outputs = 12-bit = 4096 steps // 2.5% of 20ms = 0.5ms ; 12.5% of 20ms = 2.5ms // 2.5% of 4096 = 102 steps; 12.5% of 4096 = 512 steps PCA9685_ServoEvaluator pwmServo(102, 470); // (-90deg, +90deg) // Second Servo PCA9685_ServoEvaluator pwmServo2(102, 310, 505); // (0deg, 90deg, 180deg) void setup() { Wire.begin(); // Wire must be started first Wire.setClock(400000); // Supported baud rates are 100kHz, 400kHz, and 1000kHz driver.resetDevices(); // Software resets all PCA9685 devices on Wire line driver.init(B000000); // Address pins A5-A0 set to B000000 driver.setPWMFrequency(50); // Set frequency to 50Hz } void loop() { driver.setChannelPWM(0, pwmServo.pwmForAngle(-90)); delay(1000); driver.setChannelPWM(0, pwmServo.pwmForAngle(0)); delay(1000); driver.setChannelPWM(0, pwmServo.pwmForAngle(90)); delay(1000); }

Code language: Arduino (arduino)

So we should create separate PCA9685 object for each driver, define the addresses for each driver as well as set the frequency to 50Hz. Now simply using the setChannelPWM() and pwmForAngle() functions we can set any servo at any driver to position any angle we want.

Arduino Example 2 – Controlling Servo with a Potentiometer

Our next example involves including a potentiometer so that we can manually adjust the servo’s position. This project can be extremely helpful when controlling the pan and tilt of a sensor connected to a servo.

Wiring

We’ll reuse the wiring from the previous example, but this time we’ll add a 10KΩ potentiometer. Connect one end of the pot to ground, the other to 5V, and the wiper to analog input A0.

Arduino Code

The code for making the servo follow the position of the knob is simpler than the code for making it sweep.


#include

int potPin = 0; int servoPin = 9; Servo servo; void setup() { servo.attach(servoPin); } void loop() { int reading = analogRead(potPin); int angle = map(reading, 0, 1023, 0, 180); servo.write(angle); }

Code Explanation

Notice that a new variable named

potPin

has been introduced.


int potPin = 0;

We start the loop function by reading the value from analog pin A0.


int reading = analogRead(potPin);

The

analogRead()

function returns a value between 0 and 1023. However, we must scale it down because the servo can only rotate 180 degrees.

One method is to use the Arduino map() function, which remaps a number from one range to another. The line below converts the reading to degrees between 0 and 180.


int angle = map(reading, 0, 1023, 0, 180);

Finally, we use the

write()

command to update the servo’s position to the angle selected by the potentiometer.


servo.write(angle);

DIY Servo Robotic Arm | Record and play | Arduino projet
DIY Servo Robotic Arm | Record and play | Arduino projet

Step 1: How to Connect Them

A servo motor has everything built in: a motor, a feedback circuit, and most important, a motor driver. It just needs one power line, one ground, and one control pin.

Following are the steps to connect a servo motor to the Arduino:

  1. The servo motor has a female connector with three pins. The darkest or even black one is usually the ground. Connect this to the Arduino GND.
  2. Connect the power cable that in all standards should be red to 5V on the Arduino.
  3. Connect the remaining line on the servo connector to a digital pin on the Arduino.

Check the image for a view of the servo connected to the Arduino.

Powering Servo Motors

Servo motors have different power requirements depending on their size and the workload they are experiencing. A common servo motor such as the Feetech Mini Servo Motor requires between 4.8 – 6 V at 5 – 6 mA when idle. It doesn’t take very much energy to stand still.

But as soon as the motor starts moving, it starts using more energy, and it gets that energy by pulling more current from the power source.

If it experiences heavier loads such as added weight or an object blocking its movement , it naturally needs to use even more energy to move the obstacle, and as a result the current consumption increases. The current consumption of the motor linked above can reach up to 800 mA.

This high current-draw is generally not safe to draw from an Arduino board. To avoid damaging our board we need to power the servo motor through an external power supply. Choosing the correct power supply depends on the servo motor you are using, so always check the specifications. Pay especially close attention to the:

  • operating voltage range
  • idle current – consumption when not moving
  • running current – consumption when moving freely
  • stall current – consumption under max load or when blocked

To power a 4.8 – 6 V servo you could use a 5 V 1 A AC Adapter, cut the cable, and connect the wires to the servo using e.g. a breadboard.

Note that USB wall chargers are limited to 500 mA (USB 2.0) or 900 mA (USB 3.0).

If your project needs to move around freely without being attached to a power outlet you can also choose batteries to power the servo. If you need 5 V exactly you can use two 18650 Li-Ion batteries together with a step-down converter.

A step-down converter is needed because 18650 Li-Ion batteries will give you around 7.4 V. The max current depends on the specific battery but most of them are designed to output above 1A which is enough to power our small servo.

If you are using bigger or more servos make sure to check your power requirements accordingly.

Capacitors are recommended for powering servo motors. They help stabilize the power supply, minimize voltage drops, and reduce electrical noise. The specific capacitor values may vary based on the servo motor’s requirements, but including them is good practice for better performance and reliability.

When using a Feetech Mini Servo Motor we recommend using a 100 µF capacitor.

Because some capacitors are polarised (meaning that they have a direction), you may need to be careful with how you connect them to your circuit. Make sure to connect them correctly by checking for markings such as a white stripe, a ‘+’ symbol, or a longer lead. If your capacitor has these, match the indicators of the capacitor with your circuit (pay attention to the + and – signs), and be careful not to exceed the voltage limits. This precaution helps prevent issues like leaks or damage that could harm your circuit.

You can read more about capacitors here.

Servo Motor Control with Arduino : Tutorial 63
Servo Motor Control with Arduino : Tutorial 63

Step 4: More Things About Servos

Controlling servos is easy, and here are a few more tricks we can use:

Controlling the exact pulse time

Arduino has a built-in function servo.write(degrees) that simplifies the control of servos. However, not all servos respect the same timings for all positions. Usually, 1 millisecond means 0 degrees, 1.5 milliseconds mean 90 degrees, and, of course, 2 milliseconds mean 180 degrees. Some servos have smaller or larger ranges.

For better control, we can use the servo.writeMicroseconds(us) function, which takes the exact number of microseconds as a parameter. Remember, 1 millisecond equals 1,000 microseconds.

More servos

In order to use more than one servo, we need to declare multiple servo objects, attach different pins to each one, and address each servo individually. First, we need to declare the servo objects—as many as we need:

// Create servo objects Servo Servo1, Servo2, Servo3;

Then we need to attach each object to one servo motor. Remember, every servo motor uses an individual pin:

Servo1.attach(servoPin1); Servo2.attach(servoPin2); Servo3.attach(servoPin3);

In the end, we just have to address each servo object individually:

Servo1.write(0); // Set Servo 1 to 0 degrees Servo2.write(90); // Set Servo 2 to 90 degrees

Connection-wise, the grounds from the servos go to GND on the Arduino, the servo power to 5V or VIN (depending on the power input), and in the end, each signal line has to be connected to a different digital pin. Contrary to popular belief, servos don’t need to be controlled by PWM pins—any digital pin will work.

Continuous rotation servos

There is a special breed of servos labelled as continuous rotation servos. While a normal servo goes to a specific position depending on the input signal, a continuous rotation servo either rotates clockwise or counter-clockwise at a speed proportional to the signal. For example, the Servo1.write(0) function will make the servomotor spin counter-clockwise at full speed. The Servo1.write(90) function will stop the motor and Servo1.write(180) will turn the motor clockwise at full speed.

There are multiple uses for such servos; however, they are really slow. If you are building a microwave and need a motor to turn the food, this is your choice. But be careful, microwaves are dangerous!

Servo Motor Control Arduino Code

Now let’s take a look at the Arduino code for controlling the servo motor. The code is very simple. We just need to define the pin to which the servo is connect, define that pin as an output, and in the loop section generate pulses with the specific duration and frequency as we explained earlier.


/* Servo Motor Control - 50Hz Pulse Train Generator by Dejan, https://howtomechatronics.com */ void setup() { pinMode(servoPin, OUTPUT); } void loop() { // A pulse each 20ms digitalWrite(servoPin, HIGH); delayMicroseconds(1450); // Duration of the pusle in microseconds digitalWrite(servoPin, LOW); delayMicroseconds(18550); // 20ms - duration of the pusle // Pulses duration: 600 - 0deg; 1450 - 90deg; 2300 - 180deg }

Code language: Arduino (arduino)

After some testing I came up with the following values for the duration of the pulses that work with my servo. Pulses with 0.6ms duration corresponded to 0 degrees position, 1.45ms to 90 degrees and 2.3ms to 180 degrees.

I connected a multimeter in series with the servo to check the current draw. The maximum current draw that I noticed was up to 0.63A at stall. Well that’s because this isn’t the original TowerPro MG996R servo, but a cheaper replica, which obviously has worse performance.

Nevertheless, let’s take a look at a more convenient way of controlling servos using Arduino. That’s using the Arduino servo library.


/* Servo Motor Control using the Arduino Servo Library by Dejan, https://howtomechatronics.com */ Servo myservo; // create servo object to control a servo void setup() { myservo.attach(9,600,2300); // (pin, min, max) } void loop() { myservo.write(0); // tell servo to go to a particular angle delay(1000); myservo.write(90); delay(500); myservo.write(135); delay(500); myservo.write(180); delay(1500); }

Code language: Arduino (arduino)

Here we just need to include the library, define the servo object, and using the attach() function define the pin to which the servo is connected as well as define the minimum and maximum values of the pulses durations. Then using the write() function we simply set the position of the servo from 0 to 180 degrees.

How to Make ANY servo rotate 360° - EASY and FAST
How to Make ANY servo rotate 360° – EASY and FAST

Step 5: Check Out More

More topics regarding motors such as brushless, transistor drivers ormotor speed control can be found in my Arduino Development Cookbook available here. 😀

Usage

This library allows an Arduino board to control RC (hobby) servo motors. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos allow the rotation of the shaft to be set to various speeds.

The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables

analogWrite()

(PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.

To use this library:


#include

Circuit

Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow, orange or white and should be connected to a digital pin on the Arduino board. Note that servos draw considerable power, so if you need to drive more than one or two, you’ll probably need to power them from a separate supply (i.e. not the 5V pin on your Arduino). Be sure to connect the grounds of the Arduino and external power supply together.

Usage

This library allows an Arduino board to control RC (hobby) servo motors. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos allow the rotation of the shaft to be set to various speeds.

The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables

analogWrite()

(PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.

To use this library:


#include

Circuit

Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino board. The ground wire is typically black or brown and should be connected to a ground pin on the Arduino board. The signal pin is typically yellow, orange or white and should be connected to a digital pin on the Arduino board. Note that servos draw considerable power, so if you need to drive more than one or two, you’ll probably need to power them from a separate supply (i.e. not the 5V pin on your Arduino). Be sure to connect the grounds of the Arduino and external power supply together.

There are many motors to pick from, but it’s important to pick the right one for the job. If your project requires precise positioning, a servo motor is usually the best option. Instruct them where to point, and they’ll do it for you. It’s as simple as that!

They’re useful in a variety of robotics projects, such as steering an RC model’s front wheels or pivoting a sensor on a robotic vehicle.

Troubleshooting

Sometimes, your servo may misbehave, especially if you decide to operate it directly from the Arduino. The reason for this is that the servo consumes a significant amount of power, particularly during startup, which can cause the Arduino board to reset.

To solve this problem, place a relatively large electrolytic decoupling capacitor (470µF – 1000µF) across the input power. Make sure the capacitor’s longer lead is connected to 5V and the negative lead is connected to GND.

The capacitor stores electric charge, so when the motor starts, it draws power from both the Arduino supply and the capacitor, ensuring a smooth flow of current.

Arduino #9 - Servo Selection & Motion Control
Arduino #9 – Servo Selection & Motion Control

Powering Servo Motors

Servo motors have different power requirements depending on their size and the workload they are experiencing. A common servo motor such as the Feetech Mini Servo Motor requires between 4.8 – 6 V at 5 – 6 mA when idle. It doesn’t take very much energy to stand still.

But as soon as the motor starts moving, it starts using more energy, and it gets that energy by pulling more current from the power source.

If it experiences heavier loads such as added weight or an object blocking its movement , it naturally needs to use even more energy to move the obstacle, and as a result the current consumption increases. The current consumption of the motor linked above can reach up to 800 mA.

This high current-draw is generally not safe to draw from an Arduino board. To avoid damaging our board we need to power the servo motor through an external power supply. Choosing the correct power supply depends on the servo motor you are using, so always check the specifications. Pay especially close attention to the:

  • operating voltage range
  • idle current – consumption when not moving
  • running current – consumption when moving freely
  • stall current – consumption under max load or when blocked

To power a 4.8 – 6 V servo you could use a 5 V 1 A AC Adapter, cut the cable, and connect the wires to the servo using e.g. a breadboard.

Note that USB wall chargers are limited to 500 mA (USB 2.0) or 900 mA (USB 3.0).

If your project needs to move around freely without being attached to a power outlet you can also choose batteries to power the servo. If you need 5 V exactly you can use two 18650 Li-Ion batteries together with a step-down converter.

A step-down converter is needed because 18650 Li-Ion batteries will give you around 7.4 V. The max current depends on the specific battery but most of them are designed to output above 1A which is enough to power our small servo.

If you are using bigger or more servos make sure to check your power requirements accordingly.

Capacitors are recommended for powering servo motors. They help stabilize the power supply, minimize voltage drops, and reduce electrical noise. The specific capacitor values may vary based on the servo motor’s requirements, but including them is good practice for better performance and reliability.

When using a Feetech Mini Servo Motor we recommend using a 100 µF capacitor.

Because some capacitors are polarised (meaning that they have a direction), you may need to be careful with how you connect them to your circuit. Make sure to connect them correctly by checking for markings such as a white stripe, a ‘+’ symbol, or a longer lead. If your capacitor has these, match the indicators of the capacitor with your circuit (pay attention to the + and – signs), and be careful not to exceed the voltage limits. This precaution helps prevent issues like leaks or damage that could harm your circuit.

You can read more about capacitors here.

Arduino Example 1 – Sweep

To get started, we will use one of the Arduino IDE’s built-in examples. Navigate to the Examples sub-menu. Select the Servo and load the Sweep sketch.

Go ahead and upload the sketch. The shaft of your servo motor will begin to sweep back and forth across 180 degrees.


#include

int servoPin = 9; Servo servo; int angle = 0; // servo position in degrees void setup() { servo.attach(servoPin); } void loop() { // scan from 0 to 180 degrees for(angle = 0; angle < 180; angle++) { servo.write(angle); delay(15); } // now scan back from 180 to 0 degrees for(angle = 180; angle > 0; angle--) { servo.write(angle); delay(15); } }

Code Explanation:

Controlling servos is not a simple task, but fortunately, the Arduino IDE already includes a wonderful library called Servo. It contains simple commands that can be used to quickly instruct the servo to rotate to a specific angle.

Therefore, at the beginning of the sketch, we include this library.


#include

Then we declare the Arduino pin to which the servo motor’s control pin is connected.


int servoPin = 9;

The line below creates a servo object.


Servo servo;

You can actually define up to eight servos in this way; for example, if you had two servos, you would write:


Servo servo1; Servo servo2;

The variable

angle

is used to store the servo’s current angle in degrees.


int angle = 0;

In the setup function, we use the following command to link the

servo

object to the control pin of our servo:


servo.attach(servoPin);

The loop function has two

for

loops. The first loop will rotate the motor in one direction, while the second will rotate it in the opposite direction.

The

servo.write(angle)

function instructs the servo to update its position to the specified angle.


servo.write(angle);

Continuous Rotation Servo Motors and Arduino (Lesson #11)
Continuous Rotation Servo Motors and Arduino (Lesson #11)

Sơ đồ đấu nối

Arduino Uno Động cơ Servo SG90
5V Dây màu đỏ
GND Dây màu đen
D9 Dây màu vàng

Các linh kiện cần thiết cho dự án

TÊN LINH KIỆN SỐ LƯỢNG NƠI BÁN
Arduino Uno R3 Shopee | Cytron
Động cơ Servo SG90 Shopee | Cytron
Dây cắm 10-20 Shopee | Cytron
Breadboard Shopee | Cytron

Controlling Multiple Servo Motors with Arduino

The Arduino servo library supports controlling of up to 12 servos at the same time with most the Arduino boards, and 48 servos using the Arduino Mega board. On top of that, controlling multiple servo motors with Arduino is as easy as controlling just a single one.

Here’s an example code for controlling multiple servos:


/* Controlling multiple servo motors with Arduino by Dejan, https://howtomechatronics.com */ Servo servo1; Servo servo2; Servo servo3; Servo servo4; Servo servo5; void setup() { servo1.attach(8); servo2.attach(9); servo3.attach(10); servo4.attach(11); servo5.attach(12); } void loop() { // move all servos to position 0 servo1.write(0); servo2.write(0); servo3.write(0); servo4.write(0); servo5.write(0); delay(2000); // move all servos to position 90 servo1.write(90); servo2.write(90); servo3.write(90); servo4.write(90); servo5.write(90); delay(2000); // move all servos to position 180 servo1.write(180); servo2.write(180); servo3.write(180); servo4.write(180); servo5.write(180); delay(2000); }

Code language: Arduino (arduino)

So, we just have to create objects from the Servo class for each servo motor, and define to which Arduino pin is connected. Of course, we can set any servo to move to any position, at any time.

As an example you can also check my Arduino Ant Hexapod Robot project where I used an Arduino MEGA board to control 22 servo motors.

Servo Control With Push Button
Servo Control With Push Button

Troubleshooting

Servo motor jitters and resets my Arduino board

This is a common problem with these hobby servo motors, the SG90 Micro Servo and the MG996R. The reason for this is that, as mentioned earlier, they can draw quite significant amount of current when they are at load. This can cause the Arduino board to reset, especially if you are powering the servo directly from the Arduino 5V pin.

In order to solve this issue you can use a capacitor across the GND and the 5V pin. It will act as a decouple capacitor which will provide additional current to the system at start up when the DC motor starts.

Servo motor won’t move entire range from 0 to 180 degrees

This is another common problem with these hobby servos. As we explained earlier, a pulse width of 1ms (0.5ms) corresponds to 0 degrees position, and 2ms (2.5ms) to 180 degrees. However, these values can vary from servo to servo and between different manufacturers.

In order to solve this problem, we need to adjust the pulse width we are sending to the servo motor with the Arduino. Luckily, using the Arduino Servo library we can easily adjust the pulse widths values in the attach() function.

The attach() function can take two additional parameters, and that’s the minimum and maximum pulse width in microseconds. The default values are 544 microseconds (0.544milliseconds) for minimum (0 degrees) angle, and 2400 microseconds (2.4ms). So by adjusting these values we can fine tune the moment range of the servo.


myservo.attach(9,600,2300); // (pin, min, max)

Code language: Arduino (arduino)

Conclusion

Congratulations! That was just a few easy steps to get started with standard servo motors. Now that you have this working, you can start exploring a lot of different cool projects that uses servo motors, and perhaps start making your very own robot!

Feel free to explore the Servo further.

Suggested changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.

Control a Positional Servo Motor with an Arduino (Lesson #10)
Control a Positional Servo Motor with an Arduino (Lesson #10)

Dimensions and 3D Model

I made 3D models of the two most popular servo motors, the SG90 Micro Servo and the MG996R servo motor. You can download load them from the links below.

SG90 Micro Servo

3D Model: Download from Thangs.

Dimensions:

MG996R Servo Motor

MG996R Servo Motor 3D Model: Download from Thangs.

Dimensions:

Circuit

Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to positive pole (+) of your power source. The ground wire is typically black or brown and should be connected to the negative pole (-) of your power source.

The signal pin is typically yellow or orange and should be connected to PWM pin on the board. In these examples, it is pin number 9.

Knob Circuit

For the Knob example, wire the potentiometer so that its two outer pins are connected to power (+5V) and ground, and its middle pin is connected to

on the board. Then, connect the servo motor as shown in the circuit below.

A0

Sweep Circuit

For the Sweep example, connect the servo motor as shown in the circuit below.

Inspire Award Project 2024 |Arduino car parking |  innovative ideas
Inspire Award Project 2024 |Arduino car parking | innovative ideas

Arduino Servo Motor Control

Let’s put the above said to test and make a practical example of controlling a hobby servo using Arduino. I will use the MG996R which is a high-torque servo featuring metal gearing with stall torque of 10 kg-cm. The high torque comes at a price and that’s the stall current of the servo which is 2.5A. The running current is from 500mA to 900mA and the operating voltage is from 4.8 to 7.2V.

The current ratings indicate that we cannot directly connect this servo to the Arduino, but we must use a separate power supply for it.

Circuit Diagram

Here’s the circuit diagram for this example.

We simply need to connect the control pin of the servo to any digital pin of the Arduino board, connect the Ground and the positive wires to the external 5V power supply, and also connect the Arduino ground to the servo ground.

In case we use a smaller hobby servo, the S90 Micro Servo, it’s possible to power it directly from the 5V Arduino pin.

The S90 Micro Servo has lower current consumption, around 100-200mA no-load running current, but around 500-700mA stall current. On the other hand, the Arduino 5V pin can output only around 500mA if powered via USB, or up to 1A in powered via the barrel connector.

Even though it’s possible to run these 9g servo motors directly to Arduino, for more stable work I would suggest to always use an external power supply for them.

You can get the components needed for this example from the links below:

  • MG996R Servo Motor …………………………. Amazon / Banggood / AliExpress
  • or S90 Micro Servo ………..…………………… Amazon / Banggood / AliExpress
  • Arduino Board ……………………………………. Amazon / Banggood / AliExpress
  • 5V 2A DC Power Supply …………………..….. Amazon / Banggood / AliExpress

Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.

Examples

Knob

Controlling a servo position using a potentiometer (variable resistor).

1#include

23Servo myservo; // create servo object to control a servo45int potpin = 0; // analog pin used to connect the potentiometer6int val; // variable to read the value from the analog pin78void setup() {9 myservo.attach(9); // attaches the servo on pin 9 to the servo object10}1112void loop() {13 val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)14 val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)15 myservo.write(val); // sets the servo position according to the scaled value16 delay(15); // waits for the servo to get there17}

Sweep

Sweeps the shaft of a RC servo motor back and forth across 180 degrees.

1#include

23Servo myservo; // create servo object to control a servo4// twelve servo objects can be created on most boards56int pos = 0; // variable to store the servo position78void setup() {9 myservo.attach(9); // attaches the servo on pin 9 to the servo object10}1112void loop() {13 for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees14 // in steps of 1 degree15 myservo.write(pos); // tell servo to go to position in variable ‘pos’16 delay(15); // waits 15ms for the servo to reach the position17 }18 for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees19 myservo.write(pos); // tell servo to go to position in variable ‘pos’20 delay(15); // waits 15ms for the servo to reach the position21 }22}

Suggested changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.

Arduino | Chi tiết cách sử dụng động cơ Servo
Arduino | Chi tiết cách sử dụng động cơ Servo

Step 3: How It Works

Servos are clever devices. Using just one input pin, they receive the position from the Arduino and they go there. Internally, they have a motor driver and a feedback circuit that makes sure that the servo arm reaches the desired position. But what kind of signal do they receive on the input pin?

It is a square wave similar to PWM. Each cycle in the signal lasts for 20 milliseconds and for most of the time, the value is LOW. At the beginning of each cycle, the signal is HIGH for a time between 1 and 2 milliseconds. At 1 millisecond it represents 0 degrees and at 2 milliseconds it represents 180 degrees. In between, it represents the value from 0–180. This is a very good and reliable method. The graphic makes it a little easier to understand.

Remember that using the Servo library automatically disables PWM functionality on PWM pins 9 and 10 on the Arduino UNO and similar boards.

Code breakdown

The code simply declares the servo object and then initializes the servo by using the servo.attach() function. We shouldn’t forget to include the servo library. In the loop(), we set the servo to 0 degrees, wait, then set it to 90, and later to 180 degrees.

Wiring Servo Motor to Arduino UNO

Let’s hook the servo motor to the Arduino.

We will be using an SG90 Micro Servo Motor in our experiments. It operates on 4.8-6VDC (5V typical) and can rotate 180 degrees (90 in each direction).

It draws about 10mA when idle and 100mA to 250mA when moving, so we can power it with the Arduino’s 5-volt output.

If your servo consumes more than 250mA, consider using a separate power supply for it.

Connect the red wire to the Arduino’s 5V and the black/brown wire to ground. Finally, attach the Orange/Yellow wire to PWM enabled pin #9.

The following table lists the pin connections:

Servo Motor Arduino
5V 5V
GND GND
Control

The image below shows how to connect SG90 servo motor to the Arduino.

How Servo Motors Work & How To Control Servos using Arduino
How Servo Motors Work & How To Control Servos using Arduino

Step 5: Check Out More

More topics regarding motors such as brushless, transistor drivers ormotor speed control can be found in my Arduino Development Cookbook available here. 😀

Bài 10: Điều khiển động cơ RC Servo sử dụng Arduino

Tiếp tục trong chuỗi bài viết Khóa học lập trình Arduino Miễn Phí dành cho người nhập môn.

Trong bài viết hôm nay mình sẽ hướng dẫn các bạn làm thế nào để điều khiển góc của một động cơ Servo.

Để có thể hiểu một cách tốt nhất về động cơ RC Servo là gì? Cấu tạo và nguyên lý hoạt động ra làm sao. Các bạn xem bài viết bên dưới nhé.

Xem thêm: Động cơ RC Servo là gì?

Circuit

Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to positive pole (+) of your power source. The ground wire is typically black or brown and should be connected to the negative pole (-) of your power source.

The signal pin is typically yellow or orange and should be connected to PWM pin on the board. In these examples, it is pin number 9.

Knob Circuit

For the Knob example, wire the potentiometer so that its two outer pins are connected to power (+5V) and ground, and its middle pin is connected to

on the board. Then, connect the servo motor as shown in the circuit below.

A0

Sweep Circuit

For the Sweep example, connect the servo motor as shown in the circuit below.

Arduino 04: Attaching and Testing a Servo Motor
Arduino 04: Attaching and Testing a Servo Motor

How Servo Motors Work?

There are four main components inside of a hobby servo, a DC motor, a gearbox, a potentiometer and a control circuit. The DC motor is high speed and low torque but the gearbox reduces the speed to around 60 RPM and at the same time increases the torque.

The potentiometer is attached on the final gear or the output shaft, so as the motor rotates the potentiometer rotates as well, thus producing a voltage that is related to the absolute angle of the output shaft. In the control circuit, this potentiometer voltage is compared to the voltage coming from the signal line. If needed, the controller activates an integrated H-Bridge which enables the motor to rotate in either direction until the two signals reach a difference of zero.

A servo motor is controlled by sending a series of pulses through the signal line. The frequency of the control signal should be 50Hz or a pulse should occur every 20ms. The width of pulse determines angular position of the servo and these type of servos can usually rotate 180 degrees (they have a physical limits of travel).

Generally pulses with 1ms duration correspond to 0 degrees position, 1.5ms duration to 90 degrees and 2ms to 180 degrees. Though the minimum and maximum duration of the pulses can sometimes vary with different brands and they can be 0.5ms for 0 degrees and 2.5ms for 180 degrees position.

Read More: Stepper Motors and Arduino – The Ultimate Guide

What is a Servo and what makes it precise?

Servos are motors that allow you to precisely control physical movement because they generally move to a position rather than continuously rotating. They are simple to connect and control because the motor driver is built right into them.

Servos contain a small DC motor connected to the output shaft through gears. The output shaft drives a servo horn and is also linked to a potentiometer (pot).

The potentiometer provides position feedback to the error amplifier in the control unit, which compares the current position of the motor to the target position.

In response to the error, the control unit adjusts the motor’s current position so that it matches the desired position.

In control engineering, this mechanism is known as a servomechanism, or servo for short. It is a closed-loop control system that uses negative feedback to adjust the motor’s speed and direction to achieve the desired result.

Controlling Servo motor with Arduino and python
Controlling Servo motor with Arduino and python

Keywords searched by users: arduino uno servo motor

How To Control Servo Motor With Arduino Uno? – Quartzcomponents
How To Control Servo Motor With Arduino Uno? – Quartzcomponents
Servo Motor With Arduino Uno R3 : 5 Steps - Instructables
Servo Motor With Arduino Uno R3 : 5 Steps – Instructables
Arduino Servo Motors : 5 Steps (With Pictures) - Instructables
Arduino Servo Motors : 5 Steps (With Pictures) – Instructables
How To Control A 360 Degree Servo Motor With Arduino - Makerguides.Com
How To Control A 360 Degree Servo Motor With Arduino – Makerguides.Com
How Servo Motor Works & Interface It With Arduino - Last Minute Engineers
How Servo Motor Works & Interface It With Arduino – Last Minute Engineers
Servo Motor Interfacing And Control Using Arduino - Geeksforgeeks
Servo Motor Interfacing And Control Using Arduino – Geeksforgeeks
How To Control Servo Motors With Arduino - Complete Guide
How To Control Servo Motors With Arduino – Complete Guide
How To Control A Servo With An Arduino - Youtube
How To Control A Servo With An Arduino – Youtube
Arduino Servo Motor Interfacing With Arduino Uno | Arduino
Arduino Servo Motor Interfacing With Arduino Uno | Arduino
Sg90 Servo Motor Interfacing With Arduino Uno
Sg90 Servo Motor Interfacing With Arduino Uno
How To Control Servo Motor With Arduino Uno? – Quartzcomponents
How To Control Servo Motor With Arduino Uno? – Quartzcomponents
16 Channel Servo Motor Control Driver Board For Arduino - Sritu Hobby
16 Channel Servo Motor Control Driver Board For Arduino – Sritu Hobby
Ultrasonic Distance Measurement And Servo Motor Control With Arduino Uno -  Electronics Simplified
Ultrasonic Distance Measurement And Servo Motor Control With Arduino Uno – Electronics Simplified
How To Connect Arduino With Servo Motor | Servo Motor Operates
How To Connect Arduino With Servo Motor | Servo Motor Operates
Arduino - Sound Sensor - Servo Motor | Arduino Tutorial
Arduino – Sound Sensor – Servo Motor | Arduino Tutorial
Servo Motor Using Arduino - Youtube
Servo Motor Using Arduino – Youtube
Servo Motor Interfacing And Control Using Arduino - Geeksforgeeks
Servo Motor Interfacing And Control Using Arduino – Geeksforgeeks
Using Servo Motors With The Arduino | Dronebot Workshop
Using Servo Motors With The Arduino | Dronebot Workshop
How To Control Servo Motors With Arduino - Complete Guide
How To Control Servo Motors With Arduino – Complete Guide

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *