Chuyển tới nội dung
Home » Arduino And Servo Motor | Powering Servo Motors

Arduino And Servo Motor | Powering Servo Motors

How to Control a Servo With an Arduino

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 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 to Control a Servo With an Arduino
How to Control a Servo With an Arduino

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!

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. 😀

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

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.

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. 😀

Servo Motor Control with an Arduino

You can connect small servo motors directly to an Arduino to control the shaft position very precisely.

Because servo motors use feedback to determine the position of the shaft, you can control that position very precisely. As a result, servo motors are used to control the position of objects, rotate objects, move legs, arms or hands of robots, move sensors etc. with high precision. Servo motors are small in size, and because they have built-in circuitry to control their movement, they can be connected directly to an Arduino.

Most servo motors have the following three connections:

  • Black/Brown ground wire.
  • Red power wire (around 5V).
  • Yellow or White PWM wire.

In this experiment, we will connect the power and ground pins directly to the Arduino 5V and GND pins. The PWM input will be connected to one of the Arduino’s digital output pins.

Experiment 1

Hardware Required
  • 1 x TowerPro SG90 servo motor
  • 1 x Arduino Mega2560
  • 3 x jumper wires
Wiring Diagram

The best thing about a servo motor is that it can be connected directly to an Arduino. Connect to the motor to the Arduino as shown in the table below:

  • Servo red wire – 5V pin Arduino
  • Servo brown wire – Ground pin Arduino
  • Servo yellow wire – PWM(9) pin Arduino

Caution: Do not try to rotate the servo motor by hand, as you may damage the motor.

Code

When the program starts running, the servo motor will rotate slowly from 0 degrees to 180 degrees, one degree at a time. When the motor has rotated 180 degrees, it will begin to rotate in the other direction until it returns to the home position.

#include //Servo library Servo servo_test; //initialize a servo object for the connected servo int angle = 0; void setup() { servo_test.attach(9); // attach the signal pin of servo to pin9 of arduino } void loop() { for(angle = 0; angle < 180; angle += 1) // command to move from 0 degrees to 180 degrees { servo_test.write(angle); //command to rotate the servo to the specified angle delay(15); } delay(1000); for(angle = 180; angle>=1; angle-=5) // command to move from 180 degrees to 0 degrees { servo_test.write(angle); //command to rotate the servo to the specified angle delay(5); } delay(1000); }

Experiment 2

This experiment is essentially the same as Experiment 1, except that we have added a potentiometer for position control. The Arduino will read the voltage on the middle pin of the potentiometer and adjust the position of the servo motor shaft.

Hardware Required
  • 1 x TowerPro SG90 servo motor
  • 1 x Arduino Mega2560
  • 1 x 20kΩ potentiometer
  • 1 x breadboard
  • 6 x jumper wires
Wiring Diagram

Connect the circuit as show in the figure below:

  • Servo red wire – 5V pin Arduino
  • Servo brown wire – Ground pin Arduino
  • Servo yellow wire – PWM(9) pin Arduino
  • Potentiometer pin 1 – 5V pin Arduino
  • Potentiometer pin 3 – Ground pin Arduino
  • Potentiometer pin 2 – Analog In (A0) pin Arduino
Code

Once the program is started, rotating the potentiometer should cause the shaft of the servo motor to rotate.

#include //Servo library Servo servo_test; //initialize a servo object for the connected servo int angle = 0; int potentio = A0; // initialize the A0analog pin for potentiometer void setup() { servo_test.attach(9); // attach the signal pin of servo to pin9 of arduino } void loop() { angle = analogRead(potentio); // reading the potentiometer value between 0 and 1023 angle = map(angle, 0, 1023, 0, 179); // scaling the potentiometer value to angle value for servo between 0 and 180) servo_test.write(angle); //command to rotate the servo to the specified angle delay(5); }

Give this project a try for yourself! Get the BOM.

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.

Using Servo Motors with Arduino
Using Servo Motors with 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.

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.

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

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.

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

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

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.

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

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)

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.

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

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.

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.

How Servo Motors Work & How To Control Servos using Arduino
How Servo Motors Work & How To Control Servos using 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.

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. 😀

Arduino Tutorial 30: Understanding and Using Servos in Projects
Arduino Tutorial 30: Understanding and Using Servos in Projects

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

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!

Closed loop stepper motors -- very impressive
Closed loop stepper motors — very impressive

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ì?

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.

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

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 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.

How to Control a 12V Motor with Arduino: Easy Wiring & Code Examples
How to Control a 12V Motor with Arduino: Easy Wiring & Code Examples

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.

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.

In the world of electronics and robotics, servo motors play a crucial role in controlling mechanical movements precisely. In this blog post, we’ll delve into the basics of interfacing a servo motor with an Arduino board. Whether you’re a beginner or an experienced enthusiast, this step-by-step guide will help you understand the fundamentals of servo motor control and how to integrate it with an Arduino for your projects. After you have learned the basics you can try other Arduino servo motor projects like this robotic arm using servo motor.

You can also find other such Arduino tutorials and projects on our website.

The components which we will require for this project are

  1. Arduino Uno
  2. USB cable
  3. Servo Motor SG90
  4. Potentiometer 10k ohm
  5. Jumper wires

What is a Servo motor?

A servo motor is a type of motor used in various applications to precisely control the position, speed, and angular rotation of mechanical systems. It’s designed to provide accurate control of its output shaft, allowing for precise angular position control.Servo motors typically consist of a small DC motor, a gear train, a control circuit, and a feedback system. The feedback system, often a potentiometer or an encoder, continuously sends information about the motor’s current position back to the control circuit. This feedback allows the control circuit to adjust the motor’s movement and ensure it reaches and maintains the desired position.

Types of Servo Motors

Servo Motors are divided into two main types

  1. AC Servo Motor
  2. DC Servo Motor

AC Servo motors use an AC power source, these motors use encoders for feedback. They are known for their high-speed and high-torque capabilities, making them suitable for industrial machinery and CNC equipment.DC Servo motors use a DC power source and are often equipped with encoders for feedback. They offer precise control and are commonly used in robotics and small-scale automation.

In this tutorial, we are going to use a DC Servo Motor. If you want to learn more about different types of DC motors in general, You can do that and come back here again.DC Servo Motors are classified into two types

  1. Standard rotation Servo which moves from 0 to 180 degrees
  2. Continuous rotation Servo which moves 360 degrees

We will be using a “Tower pro-Micro Servo sg90 motor” which is a type of DC standard rotation servo motor.

What is Tower Pro SG90 Servo Motor?

The Tower Pro SG90 is a popular and widely used micro servo motor known for its compact size, lightweight design, and affordability. It’s commonly utilized in various hobbyist projects, robotics, remote-controlled vehicles, and small-scale applications that require precise control of angular motion.

Specifications of Tower Pro SG90 Servo Motor

Here are the specifications of a standard SG90 Servo we should know before getting/using a servo motor for your project:

Operating Voltage 4.8 V – 6 V
Stall Torque 1.6 kg-cm
Stall Current 650 mA
Weight 9g
Operating temperature -30 to +60 degree celsius
  • Operating Voltage: This servo motor operates within a voltage range of 4.8V to 6V. Ensure the power supply falls within this range to prevent damage or inefficient operation.
  • Stall Torque: This indicates the maximum torque output of the motor when it’s unable to rotate further. It’s the force the motor can exert at a given voltage, crucial for applications that require the motor to overcome resistance or hold positions against external forces.
  • Stall Current: Stall current refers to the amount of current drawn by a motor when it’s operating at stall or maximum load condition, and the shaft is prevented from rotating. It signifies the maximum current which the motor can draw.
  • Weight: The weight of the servo motor is essential in applications where size and weight constraints are critical, such as in drones, small robotic arms, or RC vehicles.
  • Operating Temperature:Operating temperature refers to the range of temperatures within which a device or component can safely and effectively operate without risking damage or performance degradation.

SG90 Servo Motor Pinout

  • GND Ground (Brown Wire) – This is the ground pin.
  • VCC +5V (Red Wire) – Voltage is supplied to the servo motor through this Pin.
  • Control (Orange Wire) – Through this wire, Position control signals are received via PWM.

Servo Motor Working

A servo motor receives PWM (Pulse Width Modulation) signals to determine its angle of rotation. The PWM signal is a square wave with a variable duty cycle, where the width or duration of the high signal (the “on” time) corresponds to a specific angle. This signal is usually generated by a microcontroller, such as an Arduino.

When the PWM signal is fed to the servo motor’s control input (usually the orange or yellow wire), the motor’s control circuit interprets it as a command to move to a particular angle. The control circuit measures the duration of the high part of the PWM signal, which corresponds to the desired angle. This duration is typically in the range of 1 to 2 milliseconds.

The control circuit then compares this measured duration with the center position (typically 1.5 milliseconds) and adjusts the motor’s shaft to move towards the desired angle. If the duration of the high part of the PWM signal is shorter than the center position, the motor turns in one direction; if it’s longer, the motor turns in the opposite direction.

The servo motor continuously adjusts its position to match the incoming PWM signal. As the duty cycle of the PWM changes, the motor’s shaft rotates accordingly. This closed-loop control mechanism ensures that the motor accurately follows the input signal, allowing for precise and repeatable angular positioning. In essence, the servo motor’s responsiveness to PWM signals enables it to execute controlled movements in various applications, from opening and closing doors to steering remote-controlled vehicles.

In addition to using the microcontroller itself, The Servo Motor can be controlled in various other ways.

Servo Shield: A servo shield is used primarily to simplify and streamline the process of controlling multiple servo motors, particularly when working with microcontroller platforms like Arduino. Here’s how a Servo Shield looks like

Servomotor driver: The Servo drivers or Arduino Servo controller boards are commonly used to control multiple servo motors in various projects, especially in robotics, automation, and lighting systems.The PCA9685 is a popular 16-channel, 12-bit PWM (Pulse Width Modulation) servo driver. We will also learn a proper implementation of controlling multiple servo using PCA9685 later in this blog.

Servo tester: A servo tester is a simple device used to manually test, calibrate, and control servo motors without the need for a microcontroller or complex programming. It’s a standalone tool that allows users to directly interface a servo motor with.

Commonly asked questions about Servo Motors

How does a servo motor differ from a regular DC motor?

Unlike a regular DC motor, a servo motor features a closed-loop control system with feedback mechanisms like potentiometers or encoders. This enables precise position control and makes it stop at a specific angle, whereas a regular DC motor doesn’t inherently have this level of precision.

Why is my servo jittering or not moving smoothly?

Jittering or erratic movement might be due to power issues, noise in the signal, or mechanical restrictions. Ensure a stable power supply, use proper wiring, and ensure the servo isn’t mechanically constrained.

Can I modify a servo motor for continuous rotation?

Yes, some servo models can be modified for continuous rotation by disconnecting the internal feedback mechanism and adjusting the control circuitry. This essentially turns the servo into a geared DC motor with position control disabled.

Circuit Diagram of Interfacing Arduino with Servo Motors and Potentiometer

The below circuit diagram shows how a arduino servo motor control can be done using a potentiometer.

  • Connect the red wire (VCC) of the servo motor to the 5V pin on the Arduino.
  • Connect the brown or black wire (GND) of the servo motor to the GND pin on the Arduino.
  • Connect the orange or yellow wire (Signal) of the servo motor to a digital PWM pin on the Arduino.
  • Connect the positive end of potentiometer to 3.3V pin of Arduino
  • Connect the GND end to the GND pin of Arduino
  • Connect the signal pin to A0 pin(or any analog input pin)

Here’s a pinout of the potentiometer for reference

Servo Motor Arduino Code

The Arduino Servo Library is a software library that simplifies the control of servo motors using Arduino boards. It provides an easy-to-use interface for managing servo motors’ movement and position without the need for intricate programming or handling complex timing functions manually.

To include the Servo Library in your code, you add “#include

” to your code.There are two important example codes which are used for testing the Servo Motor.

Arduino Servo Sweep Code

This test code rotates the servo from 0 degree to 180 degree and then rotates back from 180 to 0 degree without the need of any input from the user side.

#include

This line includes the Servo library, which provides functions and features for controlling servo motors in an Arduino sketch.

Servo myservo;

Here, a servo object named myservo is created using the Servo library. This object will be used to control a servo motor connected to the Arduino. The comment indicates that on most Arduino boards, you can create up to twelve servo objects.

int pos = 0;

An integer variable pos is declared and initialized to store the position of the servo motor.

void setup() { myservo.attach(9);

Within the setup() function, myservo.attach(9); is used to attach the servo object myservo to pin 9 of the Arduino. This line informs the Arduino that the servo is connected to pin 9 and that pin will be used to send control signals to the servo.

void loop() { for (pos = 0; pos <= 180; pos += 1) { myservo.write(pos); delay(15); }

The loop() function contains a for loop that increments the pos variable from 0 to 180 degrees in steps of 1 degree using pos += 1. Inside the loop:

myservo.write(pos);

sends the current position value stored in the pos variable to the servo, commanding it to move to that position.delay(15); pauses the program execution for 15 milliseconds to allow the servo time to reach the specified position.

for (pos = 180; pos >= 0; pos -= 1) { myservo.write(pos); delay(15); }

Following the completion of the first loop, another for loop is used to decrement the pos variable from 180 to 0 degrees in steps of 1 degree using pos -= 1. Inside this loop, the servo is commanded to move to the position specified by the pos variable, and another delay of 15 milliseconds is added between movements.

Here’s how the servo motor tinkercad simulation will look like.

Servo Knob Code

The Arduino knob code is used to control Arduino servo with potentiometer. The code initializes a servo motor on pin 5, reads the analog value from a potentiometer on A0, maps that value to an angle between 0 and 180 degrees, and continuously updates the servo’s position based on the potentiometer’s value. The small delay aids in smooth movement of the servo motor. Here’s the line by line code explantion.you can also find the complete code in the absolute bottom of the blog.

#include

This line includes the necessary library “Servo.h,” which provides functions to control servo motors using the Arduino.

Servo servoMotor;

Here, you’re declaring an object named servoMotor of the Servo class. This object will be used to control the servo motor connected to your Arduino.

void setup() { servoMotor.attach(5); }

The setup() function is a special function that is executed only once when the Arduino board is powered on or reset. Inside the setup() function, you’re using the attach() method of the servoMotor object to connect the servo motor to digital pin 5 on the Arduino. This establishes the communication between the servo motor and the Arduino. The loop() function is another special function that contains the main code to be executed repeatedly.

int potValue = analogRead(A0);

Inside the loop() function, you’re using the analogRead() function to read the analog value from analog pin A0. This value is then stored in the variable potValue.

int servoAngle = map(potValue, 0, 1023, 0, 180);

Here, you’re using the map() function to convert the analog potValue (ranging from 0 to 1023) to a desired servo angle range (0 to 180 degrees). This new value is stored in the variable servoAngle.

servoMotor.write(servoAngle); delay(15); }

The write() method of the servoMotor object is used to set the servo motor’s angle to the calculated servoAngle. A small delay of 15 milliseconds is added using the delay() function. This short delay helps ensure smoother servo motor movement and reduces jitter.

Here’s the servomotor tinkercad simulation which shows how you can control arduino servo with potentiometer

Apart from controlling servo motors with potentiometer, it is also common to control them using push buttons. Previously we have also covered how to control servo motor using push buttons you can check out the link to learn more.

Demonstration of the Project

Here’s how the project output looks like, you can see that in our servo Arduino setup the servo motors is being controlled using the potentiometer.

Controlling multiple Servo Motor using Arduino and PCA9685

The arduino uno has 6 pwm pins only, so you can control upto 6 servo motors using arduino, for more than 6 servo motor control you need to be familiar with a servo motor driver like PCA9686Controlling multiple servo motors using an Arduino and PCA9685 involves using the PCA9685 module as a servo driver, allowing you to control multiple servos simultaneously through the I2C communication protocol. Here’s a circuit diagram that shows the servo Arduino connection for 4 servo motors.

You can use the adafruit PWM Library for this. Just download this library then go to Sketch> Include> Add .Zip library and then guide it to the library download location.When that is completed, go to file>examples> Adafruit PWM Servo Driver Library > gpiotest and upload the code.

Projects using Arduino

Learn how to create a cost-effective Battery Internal Resistance Meter using an Atmel ATtiny85 microcontroller and Arduino platform. Learn step-by-step instructions, schematic diagrams, and coding techniques to accurately measure battery health through internal resistance. Make your electronics projects better with this insightful tool for better battery management and performance optimization.

Arduino Meets TM1637: Display Module Interfacing Simplified! Learn how to easily connect and program the TM1637 4 Digit Seven Segment Display Module with your Arduino. This concise guide covers wiring, coding, and potential applications, making numeric data visualization a breeze for your projects.

Illuminating Projects: Connect TSL25911 Ambient Light Sensor to Arduino! Unveil the magic of light sensing by seamlessly integrating TSL25911 with Arduino. Our guide walks you through wiring, coding, and creative applications, allowing your projects to perceive and respond to light levels effortlessly.

//Simple Arduino Servo Code

//by CircuitDigest

#include

Servo servoMotor;

void setup() {

servoMotor.attach(5);

void loop() {

int potValue = analogRead(A0);

int servoAngle = map(potValue, 0, 1023, 0, 180);

servoMotor.write(servoAngle);

delay(15); // Small delay for smooth movement

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.

AC servo controlled with Arduino
AC servo controlled with Arduino

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.

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.

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

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.

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

Turn any DC Motor into a Servo Motor
Turn any DC Motor into a Servo Motor

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.

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.

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

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.

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:

DIY robot base from broken Hoverboard / CNC & 3D Printer
DIY robot base from broken Hoverboard / CNC & 3D Printer

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

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.

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

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

Keywords searched by users: arduino and servo motor

How To Control Servo Motors With Arduino (3 Examples)
How To Control Servo Motors With Arduino (3 Examples)
How Servo Motor Works & Interface It With Arduino - Last Minute Engineers
How Servo Motor Works & Interface It With Arduino – Last Minute Engineers
How To Control Servo Motors With Arduino - Complete Guide
How To Control Servo Motors With Arduino – Complete Guide
How To Control Servo Motor Using Arduino : 8 Steps - Instructables
How To Control Servo Motor Using Arduino : 8 Steps – Instructables
Servo Motor Interfacing And Control Using Arduino - Geeksforgeeks
Servo Motor Interfacing And Control Using Arduino – Geeksforgeeks
Arduino Servo Motor Interfacing With Arduino Uno | Arduino
Arduino Servo Motor Interfacing With Arduino Uno | Arduino
Arduino Simulator - Control Servo Motor Angle Serial Monitor - Hackster.Io
Arduino Simulator – Control Servo Motor Angle Serial Monitor – Hackster.Io
Servo Motor With Arduino Uno R3 : 5 Steps - Instructables
Servo Motor With Arduino Uno R3 : 5 Steps – Instructables
Servo Motor Control With An Arduino - Projects
Servo Motor Control With An Arduino – Projects
Pwm Sg 90 Servo Motor 5V Tower Pro - The Arduino Shop For Educational And  Researc At Rs 70/Piece In Tiruvallur
Pwm Sg 90 Servo Motor 5V Tower Pro – The Arduino Shop For Educational And Researc At Rs 70/Piece In Tiruvallur
Using Servo Motors With Arduino - Youtube
Using Servo Motors With Arduino – Youtube
Basic Servo Control | Arduino Documentation
Basic Servo Control | Arduino Documentation
Sg90 Servo Motor With Arduino - Arduino Circuit
Sg90 Servo Motor With Arduino – Arduino Circuit
Using Servo Motors With The Arduino | Dronebot Workshop
Using Servo Motors With The Arduino | Dronebot Workshop
Arduino - Sound Sensor - Servo Motor | Arduino Tutorial
Arduino – Sound Sensor – Servo Motor | Arduino Tutorial
Arduino Servo Motors : 5 Steps (With Pictures) - Instructables
Arduino Servo Motors : 5 Steps (With Pictures) – Instructables

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 *