Chuyển tới nội dung
Home » Micro Servo Motor Arduino | Step 4: More Things About Servos

Micro Servo Motor Arduino | Step 4: More Things About Servos

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!

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

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.

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

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.

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)

Arduino Tutorial: Using a Servo SG90 with Arduino
Arduino Tutorial: Using a Servo 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.

Đây là động cơ servo micro có bánh răng bằng nhựa dành cho RC, có mô men lực là 1.80kg.cm tại 4.8V. Nó là một giải pháp hoàn hảo cho các dự án robot của học sinh như lắp ráp cánh tay robot. Ưu điểm của động cơ servo RC so với động cơ chổi than DC là khả năng điều khiển góc quay của nó.

Thông số kỹ thuật:

  • Nguồn gốc: Trung Quốc

  • Tương thích với thư viện Arduino Servo.

  • Bánh răng nhựa

  • Điện áp hoạt động: 4.8 – 5VDC

  • Tốc độ 4.80V(không tải): 0.12 s/60°

  • Mô men lực 4.80V : 1.8 kg.cm (~0.1765 N.m)

  • Góc quay: 180 độ

  • Kích thước: 23.0 x12.2 x 29.0mm

  • Trọng lượng: 9.0g

  • Hệ thống dây điện:

    • Nâu = GND

    • ĐỎ = 5V

    • Cam = Tín hiệu

Hướng dẫn:

Bộ sản phẩm bao gồm:

  • 1 x Micro Servo SG90
  • 1 x Sừng Servo và phụ kiện

Thời hạn bảo hành: 12 tháng

Using the SG90 Servo Motor With an Arduino

Hi guys, today, I will show you how to use a servo motor with an Arduino. This tutorial is ideal for beginners because it is easy and it gives them the foundation to build interesting projects like robots for which servos are commonly used.

Servo motors are high torque motors which are commonly used in robotics and several other applications due to the fact that it’s easy to control their rotation. Servo motors have a geared output shaft which can be electrically controlled to turn one (1) degree at a time. For the sake of control, unlike normal DC motors, servo motors usually have an additional pin asides the two power pins (Vcc and GND) which is the signal pin. The signal pin is used to control the servo motor, turning its shaft to any desired angle.

For this tutorial, we will be using the popular SG90 servo motor and our goal will be to rotate the servo motor from one end to the other.

Servo’s have high current requirement so when using more than one servo motor with the Arduino, it is important to connect their power connections to an external power supply as the Arduino may not be able to source the current needed for the servo. Since we will be using just one servo in this tutorial its fine to power it with an Arduino.

Required Components

The following components are required to build this project:

  1. SG90 Servo
  2. Cheap Arduino Uno
  3. Wires
  4. Breadboard

Each of these components can be bought via the link attached to them.

Schematics

The schematics for this project is quite simple as we will be connecting just the servo motor to the Arduino.

Servo motors generally have three pins/wires, this includes the VCC, GND, and the Signal pin. The Signal pin is the one used to feed the control signal from the microcontroller to the servo, to get the servo rotate to a particular angle.

Connect the Servo to the Arduino as shown in the schematics below.

For emphasis, the connection is further described below.

SG90 Servo – Arduino

VCC(Red wire) – 5V SIG(yellow/orange) – D8 GND(Black/Brown) – GND

The signal pin was connected to the digital pin 8 of the Arduino because it is a PWM pin. Servo directions are sent from the microcontroller to the servo motor as PWM pulses.

With the connection all done, we can now proceed to write the code for the project.

Code

The code for this project is quite easy thanks to the very comprehensive and concise servo.h library developed by the Arduino team to facilitate the use of servo motors in Arduino projects. The library makes it easy to turn the servo at different angles using a single command. The library comes pre-installed in the Arduino IDE removing the need for us to download and install.

We start the code for the project by including the libraries that we will use which in this case is the servo.h library.

#include

Next, we create an object of the library, to be used as a reference for controlling our servo motor throughout the code.

Servo servo;

With this done, we proceed to the void setup() function. we start the function by attaching the servo object created to pin D8 of the microcontroller, after which we center the servo, turning it to zero degrees.

void setup() { servo.attach(8); servo.write(angle); }

With that done, we are ready to move the servo in any direction we desire, and we will be doing this under the void loop function. Thanks, to the servo.h library all we need to do, to rotate the servo to an angle we desire, is to pass the desired angle as an argument into the servo.write() function. To demonstrate this, a for-loop was used to turn the servos at several angles in one direction and another loop was used to turn the servo back to where it started.

void loop() { // scan from 0 to 180 degrees for(angle = 10; angle < 180; angle++) { servo.write(angle); delay(15); } // now scan back from 180 to 0 degrees for(angle = 180; angle > 10; angle–) { servo.write(angle); delay(15); } }

The complete code for the project is available below and can be downloaded from the download section at the end of the tutorial.

#include

Servo servo; int angle = 10; void setup() { servo.attach(8); servo.write(angle); } void loop() { // scan from 0 to 180 degrees for(angle = 10; angle < 180; angle++) { servo.write(angle); delay(15); } // now scan back from 180 to 0 degrees for(angle = 180; angle > 10; angle–) { servo.write(angle); delay(15); } }

Demo

Copy the code above and upload to your Arduino and servo motor setup, after a few time, you should see the servo motor start turning as shown in the gif below.

That’s it for this tutorial guys, the code above can be expanded in several ways for use in different projects involving servo motors, what cool thing will you be building with the servo motor? feel free to share via the comment section.

The video tutorial for this project can be watched on youtube.

In your article on page https://www.electronics-lab.com/project/using-sg90-servo-motor-arduino/ is listed at “REQUIRED COMPONENTS”: Distance Sensor.But this sensor is not connected and how it works.

Hi, thanks for the share, just wanted to remind that Pin 8 is not a PWM pin.

I’dont understand that part. In every site I look (but this) they say you need pwm pin. But It works even if you use pin 2 or 8 for example, and they are not pwm.

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.

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

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

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}

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
Arduino UNO Tutorial #3 - Servo Motor Project (Set Up)
Arduino UNO Tutorial #3 – Servo Motor Project (Set Up)

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.

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.

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.

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

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!

Arduino tutorial |  How to control servo motor with joystick and arduino
Arduino tutorial | How to control servo motor with joystick and arduino

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

Multiple Servo Motor Control with Joystick and Arduino
Multiple Servo Motor Control with Joystick and Arduino

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:

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

Como usar um servomotor #ManualMaker Aula 10, Vídeo 1
Como usar um servomotor #ManualMaker Aula 10, Vídeo 1

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.

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?

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.

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

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.

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

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

AC servo controlled with Arduino
AC servo controlled with 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.

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

Servo Control With Push Button
Servo Control With Push Button

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

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
Exploring a Micro stepper motor
Exploring a Micro stepper motor

Keywords searched by users: micro servo motor arduino

How To Control Servo Motors With Arduino (3 Examples)
How To Control Servo Motors With Arduino (3 Examples)
How To Control Servo Motor With Arduino Uno? – Quartzcomponents
How To Control Servo Motor With Arduino Uno? – Quartzcomponents
Working With A Micro Servo - Hackster.Io
Working With A Micro Servo – Hackster.Io
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
Arduino Servo Motor Interfacing With Arduino Uno | Arduino
Arduino Servo Motor Interfacing With Arduino Uno | Arduino
Sg90 Servo Motor With Arduino - Arduino Circuit
Sg90 Servo Motor With Arduino – Arduino Circuit
Getting Started With Servo Motors Using An Arduino – Makersupplies Singapore
Getting Started With Servo Motors Using An Arduino – Makersupplies Singapore
How To Control Servo Motors With Arduino - Complete Guide
How To Control Servo Motors With Arduino – Complete Guide
How To Control A Servo Motor With Arduino - Youtube
How To Control A Servo Motor With Arduino – Youtube
Using The Sg90 Servo Motor With An Arduino - Electronics-Lab.Com
Using The Sg90 Servo Motor With An Arduino – Electronics-Lab.Com
How To Control Servo Motor With Arduino With And Without Potentiometer -  Youtube
How To Control Servo Motor With Arduino With And Without Potentiometer – Youtube
Lonely Binary Mg90S Sg90 Metal Gear Micro Servo Motor Arduino Uno Raspberry  Pi | Ebay
Lonely Binary Mg90S Sg90 Metal Gear Micro Servo Motor Arduino Uno Raspberry Pi | Ebay
Techmahoday Micro Servo Motor For Arduino,Rc Plane,Robots (1 Pieces) Servo  Motors/Blue Color For Project : Amazon.In: Toys & Games
Techmahoday Micro Servo Motor For Arduino,Rc Plane,Robots (1 Pieces) Servo Motors/Blue Color For Project : Amazon.In: Toys & Games
Arduino - Sound Sensor - Servo Motor | Arduino Tutorial
Arduino – Sound Sensor – Servo Motor | Arduino Tutorial
How Servo Motor Works & Interface It With Arduino - Last Minute Engineers
How Servo Motor Works & Interface It With Arduino – Last Minute Engineers
Using Servo Motors With The Arduino | Dronebot Workshop
Using Servo Motors With The Arduino | Dronebot Workshop
Using The Sg90 Servo Motor With An Arduino - Electronics-Lab.Com
Using The Sg90 Servo Motor With An Arduino – Electronics-Lab.Com
Arduino Raspberry Pi 9G Sg90 180 Degree Plastic Gear Micro Servo Motor With  Accessories ( 0, 90,
Arduino Raspberry Pi 9G Sg90 180 Degree Plastic Gear Micro Servo Motor With Accessories ( 0, 90,

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 *