Arduino servos

Arduino servos DEFAULT

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

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.

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 <Servo.h> // 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.

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.

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!

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

7 People Made This Project!

Did you make this project? Share it with us!

Recommendations

  • Back to School: Student Design Challenge

    Back to School: Student Design Challenge
  • Plastic Challenge

    Plastic Challenge
  • Pumpkins & Gourds Speed Challenge

    Pumpkins & Gourds Speed Challenge
Sours: https://www.instructables.com/Arduino-Servo-Motors/

How to Use Servo Motors with Arduino © GPL3+

Servo motors are used for making things like:

  • And useless robots like this :)

What is a servo motor?

A servo motor is a motor that works in angles between 0° and 180°.

A servo motor is a motor that can only be controlled by a microcontroller like:

It has a small DC motor which only needs about 35 mA. It also has some gears and a potentiometer so that it can know which angle it's on.

Components

You'll need:

  • An Arduino/Genuino (any Arduino/Genuino will do as long as it's 9th pin is a PWM pin)
  • 5V 1A power source (you won't need this if you are using SG90 TowerPro Servo Motor

Connections

If you are using a SG90 TowerPro Servo Motor, connect the servo motor like this:

  • Signal cable (orange one) ==> D9 on Arduino
  • Power cable (red one) ==> 5v pin on Arduino
  • Ground cable (black or brown one) ==> ground pin on Arduino

If you are not using a SG90 TowerPro Servo Motor, connect the servo motor and the power source like this:

  • Signal cable (orange one) ==> D9 on Arduino
  • Power cable (red one) ==> 5v pin of power source
  • Ground cable (black or brown one) ==> ground pin of power source
  • Ground pin of Arduino ==> ground pin of power source

What are the functions in Servo library?

These are the functions in Servo library:

x = the name that you'll use when calling the servo to do something.

x = the name that you'll use when calling the servo to do something.

y = the pin to attach servo.

x = the name that you'll use when calling the servo to do something.

pos = the angle that you want your servo motor to go. (it has to be something between 0° and 180°.

Sours: https://create.arduino.cc/projecthub/arcaegecengiz/how-to-use-servo-motors-with-arduino-b02bed
  1. Trail vision camper
  2. Ct5 v blackwing
  3. Prepaid phones black friday 2020

In this tutorial we will learn how servo motors work and how to control servos using Arduino and PCA9685 PWM driver. You can watch the following video or read the written tutorial below.

Overview

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

Closed-loop System

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.

Servo Motor Closed Loop System

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.

Controlling multiple servo motors with Arduino and PCA9685 PWM Driver

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.

Robotic Arm Hexapod Humanoid Robot

How RC / Hobby Servo Work

Inside a hobby servo there are four main components, 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.

How Hobby Servo Works Inside Components DC Motor Potentiometer Control Circuit

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

RC Servo Motor Control Signal

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.

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.

Arduino Servo Motor Control MG996R

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

Arduino servo motor control circuit diagram

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.

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

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

Arduino Servo Motor Control 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 */ #define servoPin 9 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 }

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.

MG996R Servo Motor Current Draw

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 */ #include <Servo.h> 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); }

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. With this library we can drive up to 12 servos at the same time or 48 servos using Arduino Mega board.

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.

Arduino and PCA9685 PWM Servo Driver

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.

PCA9685 Address Select Pins Table I2CAddress

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

Arduino and PCA9685 Circuit Schematic

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

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.

PCA9685 Arduino Code

/* Servo Motor Control using Arduino and PCA9685 Driver by Dejan, https://howtomechatronics.com Library: https://github.com/NachtRaveVL/PCA9685-Arduino */ #include <Wire.h> #include "PCA9685.h" 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); }

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. In my case values from 102 to 470 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.

Controlling multiple servo motors with Arduino and PCA9685

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:

Multiple PCA9685 Drivers Daisy Chained Circuit

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 */ #include <Wire.h> #include "PCA9685.h" 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); }

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.

So that would be all for this tutorial, I hope you enjoyed it and learned something new. Feel free to ask any question in the comments section below and make sure you can my Arduino Projects Collection.

Categories How It WorksSours: https://howtomechatronics.com/how-it-works/how-servo-motors-work-how-to-control-servos-using-arduino/
Turnout Control With Arduino And Servos Using A PCA9685

What is a Servo Motor?

We have built a few projects that have used motors to make things move and along the way we have looked at some of the different types of motors that we can control with our Arduino and Raspberry Pi projects.

We have worked with basic DC motors a few times. We built a couple of robotics projects that are based upon DC motors and we also took an extensive look at the H-Bridge Controller that is commonly used to regulate the speed and direction of a DC motor with a microcontroller or microcomputer.

Another type of motor we’ve worked with is the stepper motor. This type of motor has its shaft driven in discrete steps, allowing for very precise control. They are widely used in printer  and robotics designs.

There is another type of motor that we have used in many of our experiments but have not (yet) taken a detailed look at – the Servo Motor.

Servo Motors with Arduino

A Servo Motor is a low-speed, high-torque motor that comes in a variety of sizes. Unlike the DC and Stepper motors the Servo Motor does not normally spin a full 360 degree rotation. Instead it is limited to a range of 180, 270 or 90 degrees.

A control signal is sent to the servo to position the shaft at the desired angle. This arrangement with a single signal makes it simple fo servos to be used in radio and remote controlled designs, as well as with microcontrollers.

A servo is perfect if you need to position the rudder on a boat or the elevator on an aeroplane.  They are really useful in robotic work to position cameras, sensors or robot appendages.

Servos can also be used as analog gauges like speedometers and tachometers.

Types of Servo Motors

A servo motor is essentially a motor that has an input for a control signal that is used to specify the position of the motor shaft.

Servos are used in industry as well as in hobby applications. Industrial servos are often AC motors with digital control inputs that cost hundreds or thousands of dollars.

We will NOT be working with industrial servo motors today!

Hobbyist servo motors are generally DC motors that can be controlled with either a digital or analog signal.

Digital servos are used in applications that require quick responses like the elevator on an aeroplane or the rudder on a helicopter.  We will NOT be working with these types of motors either, although the hookup and code used to drive them with an Arduino is identical to what we will use for our analog servos.

We will be using plain ordinary analog servo motors, the most popular type for hobbyist use. They are inexpensive and easy to obtain. Mounting hardware is also very easy to find as these servos are of a standard set of sizes.

It should be noted however that while we won’t be working with digital servo motors today they are really very much like their analog counterparts. They use the same PWM control signals as analog servo motors and can be controlled using the same circuitry and code.

Analog Servo Motors

Analog servo motors are inexpensive and available in a variety of sizes and ratings. Perfect when you need a tiny high-torque motor that can be accurately positioned and that won’t break the bank.

The “analog” part of the analog servo motor is the control signal. Analog servo motors respond to a Pulse Width Modulation or PWM signal to position their motor shaft.

PWM is an ideal control medium. It can be generated by a simple timer circuit or with a microcontroller. It can be sent over a single wire or transmitted on a radio or light beam.

The Arduino has a number of PWM capable output pins, making it ideal for controlling servo motors.

How do Servos Work?

A servo motor is a motor with a built-in “servomechanism”.

The servomechanism uses a sensor to monitor the motor shaft position and a controller to control the motor. It is fed a signal that indicates the position that the shaft should be set to. It then moves the motor into the required position.  

In the analog servo motors we will be working with that control signal is a PWM signal whose pulse width determines the angle the motor shaft is to be positioned at.  The motor itself is a simple DC motor with a lot of gearing to slow down its speed and to increase its torque.

In order to function properly the servo motor needs a sensor that can accurately measure its shaft position. On some industrial and high-end hobby servos this is done using an optical interrupter disc, but in most standard hobby servo motors the sensor is a potentiometer.  This works well as these servos typically travel 180 to 270 degrees, well within the range of a potentiometer. However the accuracy of potentiometers, especially in low cost servo motors, can affect the overall accuracy of the servomechanism.

Continuous Rotation Servo Motors

A standard analog servo motor is constricted in its rotation, usually to 180 or 270 degrees (180 is by far the most common). Its internal gearing provides a high torque power pack in a small and inexpensive package.

That combination of small size and large torque also make servos attractive to use as replacements for standard DC motors in the design of small devices like tiny toys and robots. This prompted several people to modify standard analog servos by removing the potentiometer to allow the servo to spin a full 360 degrees.

Manufactures got the message and now offer “continuous rotation servo motors”, essentially servos with the servomechanism disengaged.

In a continuous rotation servo motor the speed and direction of the shaft rotation is controlled by the same PWM signal that is used in a conventional analog servo motor.

Having a simple one-wire controls signal and the same physical package as a standard servo motor make continuous rotation servo motors attractive for a number of applications.

Servo Motor Control Signals

In order to use analog servo motors you need to understand how to control their operation using PWM. The two varieties, conventional and continuous rotation, use the same timing signals but respond to them slightly differently.

Let’s take a look at the PWM signals used in most analog servo motors.

Conventional Servo Motor Timing

In a conventional analog servo motor a PWM signal with a period of 20 ms is used to control the motors. A signal of 20 ms has a frequency of 50 Hz.

The width of the pulse is varied between 1 and 2 ms to control the motor shaft position.

Servo Motor PWM Timing

  • A pulse width of 1.5ms will cause the servo shaft to rest in the 90 degree position, the center of its travel.
  • A pulse width of 1ms will cause the servo shaft to rest at the 0 degree position.
  • A pulse width of 2ms will cause the servo shaft to rest in the 180 degree position.

Varying the pulse width between 1ms and 2ms will move the servo shaft through the full 180 degrees of its travel. You can bring it to rest at any angle you desire by adjusting the pulse width accordingly.

Continuous Rotation Servo Motor Timing

In a continuous rotation servo motor the same PWM signals will cause the motor to perform differently.

Continuous Rotation Servo Motor PWM Timing

  • A pulse width of 1.5ms will cause the servo shaft stop spinning.
  • A pulse width of 1ms will cause the servo shaft to spin at full speed counter-clockwise..
  • A pulse width of 2ms will cause the servo shaft to spin at full speed clockwise.

Varying the pulse width between 1ms and 1.5ms will make the motor spin counterclockwise with the shorter pulse widths causing the motor to spin faster.

Varying the pulse width between 1.5ms and 2ms will cause the motor to rotate clockwise with the longer pulses resulting in a faster speed.

Commercial continuous rotation servo motors will have an adjustment potentiometer that can be used to zero the speed when the motor  is feed a 1.5ms pulse width.

Servo Motor Specifications

There are literally hundreds of analog servo motors available, knowing how to read their specifications is essential to choosing the correct one for your application.

Here are some of the key parameters you’ll encounter when choosing a servo motor.

Motor Size

The physical size of a servo motor is naturally an important consideration, chances are your application will demand that the motor conform to specific size restrictions.

There are a number of standard servo motor sizes, this makes it a lot easier to find mounting brackets and hardware to accommodate your servo motor.

Servo sizes are often specified as follows:

  • Nano
  • Sub-Micro
  • Micro
  • Mini
  • Standard
  • Large

There are also specialty sizes. The Micro and Standard sizes are the ones most often used by Arduino experimenters.

Gear Material

Servos have a number of internal gears plus gearing directly on the output shaft, these serve to slow down the motor speed and increase its torque.

The gears can be manufactured using either plastic or metal.

Metal gears offer better performance, can usually support higher torques and are less subject toi stripping.  Metal gear servos also come at a higher cost.

Plastic gears are more susceptible to stripping and don’t have the torque capabilities of their metal counterparts. They are however quieter and are less expensive than metal geared servo motors.

You can often get the same servo motor with a choice of gears. A common experimenters motor is the SG90, a Micro sized servo motor with plastic gears. Its metal-geared counterpart is the MG90. As they come in the same case and have the same voltage and driver requirements they are interchangeable, with the MG90 offering superior performance because of its metal gears.

Servo motor quality is also affected by the type of bearings and the number of them. Motors with multiple bearings have smoother and more accurate rotation.

Speed

The speed of a servo motor is specified as the time required to move the shaft of the servo by 60 degrees.

Servo Motor Specs - Speed

An example rating is 0.25 sec/60°, meaning it takes a quarter of a second to travel 60 degrees.

Servo speed is more applicable to conventional servo motors, continuous rotation motors are rated in maximum RPM like any DC motor.

High speed servos are used in model aeroplane and helicopter application to control elevators and rudders which often need to be moved quickly.  Many of these use digital control and internal optical position sensors instead of potentiometers to allow for more rapid movement.

For hobby applications like controlling the position of a video camera or ultrasonic sensor speed isn’t usually a critical factor.

Torque

Torque is a very important parameter, it literally specifies how strong a motor is.

Torque is defined as the amount of force a servo can apply to a lever or in other words how much weight it can hold up.

It is measures in either ounce-inches or kilogram-centimeters. You can convert manually as follows:

  • Multiply kilogram-centimeters by 13.88 to get ounce-inches.
  • Divide ounce inches by 13.88 to get kilogram-centimeters.

Another way is to use an online torque converter.

To understand how the torque figures relate to real world conditions consider the following example:

Servo Motor Specs - Torque

A servo motor is rated at 5 kg-cm.  This would also be the same as 69.4 oz-in (5 x 13.88 = 69.4).

The servo motor can support up to 5kg of load on a lever at a distance of 1 centimeter from shaft center. If you prefer Imperial measurements then it could support a 69.4 ounce load (about 4.3 pounds) at a distance of 1 inch.

At double the distance the load would be halved, so at 2cm from the shaft the lever could support 2.5kg.

Half the distance doubles the load that can be supported to 10kg.

Larger servo motors tend to have larger torque capabilities, motors with greater torque tend to be more expensive.  They also weigh more and consume more current.

Operating Voltage

Most hobby analog servos are rated from 4.8 to 6 volts and achieve their maximum performance at the higher voltage.

There are also more servos being offered with maximum voltage ratings of 7.5 to 8.5 volts. These are becoming more popular due to the availability of 7.4 volt LiPo batteries for model aircraft, boats, vehicles and quadcopters.

Servo motors, especially high torque models, can consume quite a lot of current, this needs to be taken into account when selecting a power supply or battery for your project.

Horns, Arms and Accessories

Most servo motors have a geared shaft that is threaded for a center screw.

In order to make use of the servo you will need to connect the shift to another component in your design – a platform, a gear, a wheel or whatever it is you are trying to move with the servo.

Servo motors come with an assortment of levers and discs of different shapes that can be mated to the shaft to facilitate attaching the servo to your design. These pieces are often referred to as “horns” or “arms”.  They attach to the servo motor shaft and are secured in position with the center screw and they can be made of plastic or metal.

In addition to the horns and arms you should also receive an assortment of mounting hardware and screws with your servo, including the center screw for the shaft (don’t lose it as they tend to differ between servo types).

You can also buy mounting plates designed to accept popular servo sizes like Micro and Standard.

The availability and interchangeability of servo horns, arms, mounting hardware and accessories makes it easy to incorporate servo motors into your designs.

Testing Servo Motors

As with any component its useful to know how to test a servo motor to ensure proper operation.

This can be very helpful when you are about to mount the servo into a mission-critical application, or just into something that would be a pain to have to take apart if the servo turns out to be faulty!

It is also useful to be able to rotate the servo shaft into a preset position (for example 90 degrees) before mounting the sero into your project so that everything gets aligned correctly.

There are a number of methods you can use to test a servo. A simple Arduino sketch and connection like the ones you’ll be seeing here further on will make an excellent method of testing a servo and of positioning its shaft into a preset position.

Another way of doing this is by using a dedicated servo tester.

Servo Testers

As you might imagine a Servo Tester is a device used to test servo motors!  They are very useful and can be very inexpensive, depending upon the features you want.

A simple servo tester like the one shown here (and used in the accompanying video) can be had for just a couple of dollars.

More advance servo testers have speed and centering controls for multiple motors, some also have current meters. Even these are under 20 dollars.

These units need to be powered by the same power supply (or equivalent) that you’ll be using the power the motors themselves. They can be plugged in to a standard servo motor connector and they will take control of the servo.

The servo testers will allow you to manually move the motor and to center it at the 90 degree position. This lets you check the motor for correct operation and to align its shaft position before you fasten horns or arms to it.

Servo Motor Connections

Analog servo motors typically have a 3-pin connector. On some more expensive motors the motor cable can be removed at the motor base and replaced if required, other motors have the connector permanently wired onto a short 3-wire cable.

The color codes used on hobbyist servo motors varies depending upon manufacturer. However most manufacturers observe the same pinout, as shown in the following diagram:

Servo Motor Pinout

The three connections to the servo motors are as follows:

  1. Ground – The common ground for both the motor and logic.
  2. Power – The positive voltage that powers the servo.
  3. Control – The input for the PWM control signal.

The most common connector is the standard DuPont variety with 0.1 inch spacing. This makes it easy to connect servo motors to your project using standard DuPont header strips.

You can also insert breadboard wires directly into the servos 3-pin connector so you can prototype with servo motors.

Connecting to an Arduino

As we have already described a servo motor requires a PWM control signal to operate correctly.  You can generate this signal many ways – a simple timer circuit, a dedicated control chip or using a microcontroller with PWM output capabilities.

The microcontroller naturally has many advantages in being able to control the servo more effectively. And an Arduino is an excellent choice.

The Arduino IDE has a Servo library already included so adding a servo to your sketch is very simple as you will soon see.

PWM Output

All Arduino boards have some output pins that are capable of Pulse Width Modulation or PWM. On an Arduino Uno there are 6 PWM-capable pins.

Keep in mind that to generate the PWM signals the Servo Library will need to use some of the internal Arduino timers, specifically Timer 1.  This can interfere with other libraries that also need the same timers. One way around this is to look for alternate libraries for either the servo of=or the other desired function, this is a common way of getting around these restrictions.

A more advanced method is to use an external PWM controller board and free up the Arduino timers. This will be discussed further in this article.

Most servo motors will happily operate on 5 volts, making it tempting to use the 5-volt output on the Arduino board to power the servo.

It’s not really a very good idea.

Servos can consume a fair amount of current, especially when placed under load. This might be more current than the voltage regulator on the Arduino board can take, especially on cheaper clone boards.  While most Arduino boards can support one Micro servo it still taxes the regulator a lot.

Servo motors, like all other motors, can induce electrical noise onto the power supply lines. Having that noise on the lines powering your microcontroller and other logic devices can often lead to system errors.

It is a much better idea to use a separate power supply for your servo motor. A 5-volt USB 3  power supply would work well, as would a 6-volt lantern battery or 4 type AA or C batteries.

If you REALLY must power a servo directly from the Arduino limit it to one micro servo. A capacitor of 100uf or greater across the power supply line near the servo can help absorb those power surges.

The Sweep Sketch

For our first Arduino sketch we will use one of the built-in examples that is packaged with your Arduino IDE. No code to write or libraries to install!

Wiring up the hardware to use with our first demonstration is very simple. You’ll need an Arduino (any type), a servo motor and a power supply for the servo motor.

Arduino Sweep Sketch Servo Hookup

The hookup couldn’t be simpler. The servo is powered by its own power supply and the ground connection is also connected to the Arduino ground. Then the control lead from the servo is connected to pin 9 on the Arduino.

Pin 9 on the Arduino Uno is one of the six pins that are capable of PWM, on most Uno boards you’ll see a symbol beside the 6 PWM-enabled I/O pins.

Hook your Arduino up to your computer and start the Arduino IDE.

Click the File menu at the top of the screen.From there select the Examples sub-menu.

A list of example sketches will be displayed. It is divided into sections, scroll down the list until you get to the “Examples from Libraries” section.

In the “Examples from Libraries” section you will see “Servo”.  Highlight that to reveal two sketches, Knob and Sweep.

Load the Sweep sketch.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

/* Sweep

by BARRAGAN <http://barraganstudio.com>

This example code is in the public domain.

 

modified 8 Nov 2013

by Scott Fitzgerald

http://www.arduino.cc/en/Tutorial/Sweep

*/

 

#include <Servo.h>

 

Servo myservo;  // create servo object to control a servo

// twelve servo objects can be created on most boards

 

intpos=0;    // variable to store the servo position

 

voidsetup(){

  myservo.attach(9);  // attaches the servo on pin 9 to the servo object

}

 

voidloop(){

  for(pos=0;pos<=180;pos+=1){// goes from 0 degrees to 180 degrees

    // in steps of 1 degree

    myservo.write(pos);              // tell servo to go to position in variable 'pos'

    delay(15);                       // waits 15ms for the servo to reach the position

  }

  for(pos=180;pos>=0;pos-=1){// goes from 180 degrees to 0 degrees

    myservo.write(pos);              // tell servo to go to position in variable 'pos'

    delay(15);                       // waits 15ms for the servo to reach the position

  }

}

Sweep is a very basic sketch that just sweeps the servo shaft from one extreme to the other.

The sketch makes use of the Arduino Servo Library which is included with your Arduino IDE. As its name implies its is a library for controlling servo motors with PWM.  We include the library and define an object called myservo to represent our servo motor. If you have multiple servo motors you can define an object for each of them.

We then define a variable called “pos” that holds the position (angle) that we want the servo motor shaft to move to.

In the setup we attach our servo object to the servo motor control line on pin 9 of the Arduino.

Then the loop, which consists of two for loops.  The first loop increments the value of the pos variable and uses it to control the servo motor using a myservo.write command, sending the shaft from 0 to 180 degrees.

The second for loop is identical except it decrements the value from 180 to 0, sending the shaft back in the opposite direction.

Load the sketch into the Arduino and observe the servo motor shaft, it should be travelling from one end to the other.

You just made a servo move with an Arduino!

The Knob Sketch

Let’s move on to the other demo sketch included with the Arduino IDE, the Knob sketch. Before we do we’ll need to add a component to our circuit.

Arduino Knob Sketch - Hookup

As the wiring diagram shows you’ll need a potentiometer, any value from 10k up will work fine. Hook one end of the pot to ground, the other end to the Arduino +5 volts. The wiper is connected to analog input A0.

The potentiometer will serve as a control to position the shaft of the servo motor, you can use it to dial any position on its 180 degree travel.  Not only is it a good demonstration it also can be a useful function for setting the position of servo motors before mounting them into your project.

If you substitute a continuous rotation servo in the circuit you can use the potentiometer to control both the speed and direction of the motor’s rotation.

After you modify the experiment to include the potentiometer open the Arduino IDE and go back to the example sketches. This time select Sweep from the Servo menu.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

/*

Controlling a servo position using a potentiometer (variable resistor)

by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 

modified on 8 Nov 2013

by Scott Fitzgerald

http://www.arduino.cc/en/Tutorial/Knob

*/

 

#include <Servo.h>

 

Servo myservo;  // create servo object to control a servo

 

intpotpin=0;  // analog pin used to connect the potentiometer

intval;    // variable to read the value from the analog pin

 

voidsetup(){

  myservo.attach(9);  // attaches the servo on pin 9 to the servo object

}

 

voidloop(){

  val=analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)

  val=map(val,0,1023,0,180);     // scale it to use it with the servo (value between 0 and 180)

  myservo.write(val);                  // sets the servo position according to the scaled value

  delay(15);                           // waits for the servo to get there

}

The Sweep sketch is also very simple. Like the Knob sketch it uses the Arduino Servo Library which it includes and then creates a myservo object to represent the servo motor.

We then define a couple of integers. The first one, potpin, represents the analog pin we used for the potentiometer wiper connection.  The other one, val, is the value taken when reading that analog input.

The setup is identical to the Knob sketch, we attach the servo object to pin 9.

In the loop we start by reading the value from the analog pin, a value of 0 to 1023 which will be assigned to val. Next we use the Arduino Map Function to change val to represent the angle between 0 and 180 degrees.

After that we use a write command to position the servo to the value of val, the angle selected by the potentiometer.

After a brief delay to allow the servo motor to catch up we do it all over again.

Load the sketch up to your Arduino and turn the potentiometer. You should see the shaft of the servo motor move in time with the pot.

Once again the sketch illustrates just how easy it is to control a servo with your Arduino.

PCA9685 Servo Driver Board

Controlling servo motors from an Arduino directly is pretty simple as we just saw. However it has its limitations:

  • You are limited by the number of PWM pins on your Arduino. If the servo is part of a design that requires other PWM devices that may be a problem.
  • The Arduino Servo Library can conflict with other Arduino libraries as they attempt to use the same timer. This can sometimes be solved by looking for alternative libraries.
  • You need to control a LOT of servo motors, even an Arduino Mega has its limitations here.

A better solution all around is to use a separate servo driver board. This will offload the task of sending PWM to the servos, freeing up your Arduino to do better things.

The board we will be using is based around the PCA9685 chip. These boards are extremely popular and are manufactured by several companies.

The PCA9685 board uses I2C to communicate with the Arduino. This means only two connections for clock and data are made to the Arduino. As the boards I2C address can be configured using a series of solder pads you can use many of them on the same circuit.

Each board can control up to 16 servo motors. And you can cascade up to 62 boards to control a whopping 992 servo motors!

If you honestly need to control over 992 servo motors you could use an I2C shield to connect multiple I2C buses to your Arduino!

The connections to the board are very simple.

PCA9685 Pinout Diagram

There are a set of identical connections on each side of the circuit board, this makes it easy to connect several modules up in a row.  They are as follows:

  • GND – The Ground connection.
  • OE – Output enable. You can use this pin to enable and disable all of the 16 outputs. Typically it is left unconnected which will result in all outputs being enabled.
  • SCL – The Clock line for the I2C bus.
  • SDA – The Data line for the I2C bus.
  • VCC – The logic power supply, +5 Volts.
  • V+ – the power for the servo motors. There is also another connector on top of the board for this and that connector is preferable as it is reverse polarity protected while V+ is not. The V+ pins are really used to cascade multiple PCA9685 modules and power all the servos off of a single power supply.

There is also a 2-pin screw connector at the top for the servo power supply. As mentioned above it is reverse polarity protected.

On the bottom of the board are 16 sets of 3-pin male connectors. Each one is used for a servo motor.

On the top right of the board are six solder pads. These are used to setup the I2C address for the board. If you are using more than one board you’ll need to jumper one or more of these to change its internal I2C address to be unique.

The base address for a PCA9685 module with none of the jumpers shorted is 0x40.

If you short out the A0 solder pad the address becomes 0x41.

Bridge A1 instead and it’s now an address of 0x42. Bridge both A0 and A1 and the address will be 0x43.

Multiple Servos – Controlling the MeArm

In order to demonstrate the use of the PCA9685 PWM module to control multiple servo motors I decided to bring out the MeArm which I built earlier. It has four servo motors.

I connected everything up as follows:

PCA9685 Arduino Hookup

You’ll notice that I also added four potentiometers, as before these can be any value of 10k or above and will be used to regulate the operation of each of the four servo motors.

The PCA9685 module hooks up to the SCL and SDA connections on the Arduino. If your Arduino does not have pins for these I2C connections then use analog pin A4 for SDA and pin A5 for SCL.

Note that even if you do have separate SCL and SDA pins you won’t be able to use A4 and A5 as analog inputs when using I2C.

The four potentiometers connect to ground on one side and 5 volts on the other. Their wipers connect to analog inputs A0 through A3.  

The Arduino power is also used to power the VCC power on the PCA9685 module.  A seperate power supply for the four servos is connected to the screw connector on the module.

I connected my servo motors to outputs 0, 4, 8 and 12. You can actually use any four connections, just note them so you can modify the code to match your selection.

As this is the only PCA9685 module I’ve connected to the Arduino I didn’t short out any of the address solder pads.

Now let’s look at the sketch I’m using to make this all work:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

/*

  PCA9685 PWM Servo Driver Example

  pca9685-servomotor-demo.ino

  Demonstrates use of 16 channel I2C PWM driver board with 4 servo motors

  Uses Adafruit PWM library

  Uses 4 potentiometers for input

 

  DroneBot Workshop 2018

  https://dronebotworkshop.com

*/

 

// Include Wire Library for I2C Communications

#include <Wire.h>

 

// Include Adafruit PWM Library

#include <Adafruit_PWMServoDriver.h>

 

#define MIN_PULSE_WIDTH       650

#define MAX_PULSE_WIDTH       2350

#define FREQUENCY             50

 

Adafruit_PWMServoDriver pwm=Adafruit_PWMServoDriver();

 

// Define Potentiometer Inputs

 

intcontrolA=A0;

intcontrolB=A1;

intcontrolC=A2;

intcontrolD=A3;

 

// Define Motor Outputs on PCA9685 board

 

intmotorA=0;

intmotorB=4;

intmotorC=8;

intmotorD=12;

 

voidsetup()

{

  pwm.begin();

  pwm.setPWMFreq(FREQUENCY);

}

 

 

voidmoveMotor(intcontrolIn,intmotorOut)

{

  intpulse_wide,pulse_width,potVal;

  

  // Read values from potentiometer

  potVal=analogRead(controlIn);

  

  // Convert to pulse width

  pulse_wide=map(potVal,0,1023,MIN_PULSE_WIDTH,MAX_PULSE_WIDTH);

  pulse_width=int(float(pulse_wide)/1000000*FREQUENCY *4096);

  

  //Control Motor

  pwm.setPWM(motorOut,0,pulse_width);

 

}

 

voidloop(){

 

  //Control Motor A

  moveMotor(controlA,motorA);

  

  //Control Motor B

  moveMotor(controlB,motorB);

    

  //Control Motor C

  moveMotor(controlC,motorC);

  

  //Control Motor D

  moveMotor(controlD,motorD);

 

}

The sketch makes use of the Adafruit PWM Servo Driver Library which you will need to install to make this work.  It can be installed from the Library Manager in your Arduino IDE.

  • Open the Arduino IDE.
  • Select Sketch from the menu at top.
  • Select Include Library. A sub-menu will appear.
  • Select Manage Libraries… from the sub-menu.
  • The Library Manager will open.
  • Search the Library Manager for “Adafruit PWM”
  • The Adafruit PWM Servo Library Driver should be the first result.
  • Click the More Info link to reveal an Install button. Use this button to install the library into your IDE.
  • Close the library manager.
  • The library is now installed and can be used in your IDE.

We begin the sketch by including the Wire library. This is built into your Arduino IDE and is used to control I2C communications.

Next we include the Adafruit PWM Servo Library that we just installed.

We will now define a few constants.  

The first two constants define the minimum and maximum pulse width for the PWM signal we will be sending to our servos. A you recall this pulse width will determine the position of the servo shaft.

The third constant we define is the PWM frequency, which for analog servo motors is 50 Hz.  If you are using digital servo motors you may want to increase this as they can often use frequencies as high as 200 Hz.

Next we create an object called pwm using the Adafruit PWM Library. If you used an address other than the default 0x40 you would need to define it here.

Now we define some variables. The first one is the potentiometer input pins, A0 through A3. After that are the motor outputs on the PCA9685 board, I used 0, 4, 8 and 12 when I hooked up my motors. Change these values if you used different connectors for your motors.

Now onto the Setup. We initialize the pwm object we created earlier and then set the frequency of the PWM oscillator to the frequency we defined, which in our case is 50 Hz.

Now we create a function that will drive the motors in response to the potentiometer positions.  We can then just call this function for each motor.

Our function is called moveMotor. It has two inputs, controlIn which represents the potentiometer input and motorOut which represents the motor connection on the PCA9685.

The function reads the potentiometer value and converts it to a pulse width. This pulse width is then used with the setPWM method of the Adafruit PWM Servo Library to send the pulse to the motor specified by the motorOut variable.

In the loop we just call the moveMotor function four times, once for each potentiometer-servo motor combination.

The result is that the four servo motors in the MeArm will respond to the potentiometers. In the demo I used slide potentiometers which made it a lot easier to precisely position the MeArm (I use the term “precisely” with a lot of poetic license!).

Conclusion

Servo motors are versatile little devices that have a myriad of uses in hobbyist projects and knowing how to control them is an essential Arduino coding and wiring skill.

Hopefully this article and its associated video have helped shed some light on using servo motors, either connected directly to an Arduino or via I2C using a PCA9685 PWM controller.

So grab yourself a bunch of servo motors and start making things move today!

 

 

Related

Summary

Using Servo Motors with the Arduino

Article Name

Using Servo Motors with the Arduino

Description

Learn how to use analog servo motors with the Arduino. Covers the Arduino Servo Library and using the PCA9685 PWM controller to control multiple servo motors.

Author

DroneBot Workshop

Publisher Name

DroneBot Workshop

Publisher Logo

DroneBot Workshop

Tagged on: Arduino Tutorial

DroneBot WorkshopArduino, Tutorial

Sours: https://dronebotworkshop.com/servo-motors-with-arduino/

Servos arduino

In this tutorial, you will learn how servo motors work and how to control them with Arduino. I have included wiring diagrams and several example codes! Servo motors are often used in robotics projects but you can also find them in RC cars, planes, etc. They are very useful when you need precise position control and/or high torque.

In the first part of this article, we will look at the inner workings of a servo and what type of control signal it uses. I also explain what the differences between a standard and a continuous servo are. Next, I will show you how to connect a servo motor to the Arduino.

PCBWay

With the first code example, you can control both the position as well as the speed of the servo motor. After that, we will look into controlling a servo with a potentiometer and how you can modify the code to control multiple servo motors at the same time. Lastly, at the end of this article, you can find the specifications and dimensions of some of the most popular servo motors on the market.

If you would like to learn more about other types of motors, check out the articles below:

Recommended articles

If you have any questions, please leave a comment below.


Supplies

Hardware components

Software

Makerguides.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to products on Amazon.com.


How does a servo motor work?

A standard hobby servo typically consists of a small electric motor, a potentiometer, control electronics, and a gearbox. The position of the output shaft is constantly measured by the internal potentiometer and compared with the target position set by the controller (e.g. the Arduino).

According to the error, the control electronics adjust the actual position of the output shaft so that it matches the target position. This is known as a closed-loop control system.

The gearbox decreases the speed of the motor, which increases the torque at the output shaft. The maximum speed of the output shaft is usually around 60 RPM.

Servo control

Servo motors are controlled by sending a PWM (pulse-width modulation) signal to the signal line of the servo. The width of the pulses determines the position of the output shaft. When you send the servo a signal with a pulse width of 1.5 milliseconds (ms), the servo will move to the neutral position (90 degrees). The min (0 degrees) and max (180 degrees) position typically correspond to a pulse width of 1 ms and 2 ms respectively. Note this can vary slightly between different types and brands of servo motors (e.g. 0.5 and 2.5 ms). Many servos only rotate through about 170 degrees (or even only 90) but the middle position is almost always at 1.5 ms.

For adjusting the min and max position in the code, see the section below.

Servo motors generally expect a pulse every 20 milliseconds or 50 Hz but many RC servos work fine in a range of 40 to 200 Hz.


360-degree (continuous) vs 180-degree (standard) servo

Most RC servos are from the 180-degree variety, which means that they can only rotate in a range of 0 to 180 degrees. However, continuous rotation, also known as 360-degree servo motors, are also available.

Continuous rotation servos react differently to the control signal than standard 180-degree servos. With a continuous rotation servo, you can not control the exact position of the output shaft, only the speed and the direction. A 1 ms pulse will set the speed of the servo motor to full speed in one direction and a 2 ms pulse to full speed in the other. A value near 1.5 ms lets the motor stop.

If your servo behaves in an unexpected way, you might be using a continuous servo instead of a standard one.


How to connect a servo motor to the Arduino?

Wiring a servo motor is very easy because you only need to connect three wires: power, ground, and signal. The power wire is typically red and needs to be connected to 5 V.

A micro servo like the SG90 consumes around 10 mA when it’s idle and 100 – 250 mA when rotating, so you can power it directly with the 5 V output of the Arduino. However, you need to be careful when using multiple or larger servo motors. If your motor(s) consume more than 300 mA you should use an external power supply to avoid damaging the Arduino! See the schematic below for using external power supplies.

The ground wire is typically black or brown and should be connected to the ground pin of the Arduino. When using a separate power supply, connect the ground wire to both the Arduino and the power supply ground.

The signal wire is typically yellow, orange, or white can be connected to any of the digital pins of the Arduino. In this case, I connected it to digital pin 9.

The connections are also given in the table below.

Servo motor connections

Servo motorArduino
Power (red)5 V
Ground (black or brown)GND
Signal (yellow, orange or white)Pin 9

As I mentioned before, if you are using large or multiple servo motors you should use an external power supply. Simply connect the power supply as shown in the wiring diagram below. Make sure to connect the GND pin of the Arduino and the power supply together.

You can also use this setup if your servo motor requires a different voltage than the Arduino can provide e.g. 6 V or higher.

servo-motor-with-arduino-uno-and-external-power-supply-wiring-diagram-schematic-circuit-tutorial

Servo motor with external power supply connections

Servo motorConnection
Power (red)5 V power supply
Ground (black or brown)Power supply ground and Arduino GND
Signal (yellow, orange or white)Pin 9 Arduino

Servo motor with Arduino example code

To control the servo motor we will be using the Servo.h library which comes pre-installed with the Arduino IDE. With the example code below, you can control the exact position of the servo motor and it also includes code to sweep the servo arm back and forth automatically.

You can upload the example code to your Arduino via the Arduino IDE. Next, I will explain how the code works.

You can copy the code by clicking on the button in the top right corner of the code field.

/* Servo motor with Arduino example code. Position and sweep. More info: https://www.makerguides.com/ */ // Include the servo library: #include <Servo.h> // Create a new servo object: Servo myservo; // Define the servo pin: #define servoPin 9 // Create a variable to store the servo position: int angle = 0; void setup() { // Attach the Servo variable to a pin: myservo.attach(servoPin); } void loop() { // Tell the servo to go to a particular angle: myservo.write(90); delay(1000); myservo.write(180); delay(1000); myservo.write(0); delay(1000); // Sweep from 0 to 180 degrees: for (angle = 0; angle <= 180; angle += 1) { myservo.write(angle); delay(15); } // And back from 180 to 0 degrees: for (angle = 180; angle >= 0; angle -= 1) { myservo.write(angle); delay(30); } delay(1000); }

How the code works

The first step is to include the required Arduino library. You can also find this library under Sketch > Include Library > Servo.

// Include the servo library: #include <Servo.h>

Next, you need to create a new object of the Servo class. In this case, I called the servo ‘myservo’ but you can use other names as well. Note that you will also have to change the name of the servo in the rest of the code.

// Create a new servo object: Servo myservo;

After that, I defined to which Arduino pin the servo motor is connected.

// Define the servo pin: #define servoPin 9

The statement  is used to give a name to a constant value. The compiler will replace any references to this constant with the defined value when the program is compiled. So everywhere you mention , the compiler will replace it with the value 9 when the program is compiled.

The variable is used to store the current position of the servo in degrees.

// Create a variable to store the servo position: int angle = 0;

In the setup section of the code, we link the servo object that we created to the pin that will control the servo. The function also has two optional parameters, which I discuss in the section below.

void setup() { // Attach the Servo variable to a pin: myservo.attach(servoPin); }

Control angle/position:

In the first part of the loop, we simply tell the servo motor to move to a particular angle with the function . Note that you need a delay between the commands to give the servo motor some time to move to the set position.

// Tell the servo to go to a particular angle: myservo.write(90); delay(1000); myservo.write(180); delay(1000); myservo.write(0); delay(1000);

Control speed:

In the last part of the code, I used two for loops to sweep the servo motor back and forth. This piece of code can also be useful if you want to control the speed of the servo motor. By changing the delay value at the end of the for loop, you can adjust the speed of the servo arm.

// Sweep from 0 to 180 degrees: for (angle = 0; angle <= 180; angle += 1) { myservo.write(angle); delay(15); } // And back from 180 to 0 degrees: for (angle = 180; angle >= 0; angle -= 1) { myservo.write(angle); delay(30); }

Why doesn’t my servo turn a full 0 – 180 degrees?

As I discussed in the introduction, the angle of the output shaft of the servo motor is determined by the width of the electrical pulse that is applied to the control wire. Generally, a pulse width of about 1 ms (millisecond) corresponds to the minimum position, 2 ms to the maximum position, and 1.5 ms to 90° (neutral position). However, this can vary slightly between brands and even different servos of the same brand. This means that you will have to adjust the minimum and maximum values in the code to match the servo that you are using.

The Arduino Servo library makes it very easy to tune the min and max angle of the servo motor by specifying two optional parameters in the function. In this function, the first parameter is the number of the pin that the servo is attached to. The second parameter is the pulse width, in microseconds (μs), corresponding to the minimum (0-degree) angle of the servo motor. The third parameter is the pulse width, in microseconds, corresponding to the maximum (180-degree) angle of the servo motor.

By default, the min and max pulse width is set to 544 and 2400 microseconds. These values work for most common servos, but sometimes you have to adjust the values slightly.

I recommend adjusting the min and max values in small increments (10-20 microseconds) to avoid damaging the servo. If the servo arm is hitting the physical limits of the motor, increase the min value, and decrease the max value.

#define servoPin 9 int min = 480; int max = 2500; Servo myservo; void setup() { myservo.attach(servoPin, min, max); }

Control a servo motor with a potentiometer and Arduino

servo-motor-with-arduino-uno-and-potentiometer-wiring-diagram-schematic-circuit

Controlling the position of a servo motor with a potentiometer is very easy and can be very useful if you want to adjust the motor position by hand. As you can see in the wiring diagram above, the servo motor is wired in the same way as before. The only difference is that I used a breadboard to distribute the power from the Arduino.

The potentiometer has three pins, connect the outside pins to 5 V and GND. The middle pin of the potentiometer is connected to the analog pin A0 of the Arduino.

Servo motor with potentiometer Arduino example code

The example code below lets you control a servo motor with a potentiometer.

You can copy the code by clicking on the button in the top right corner of the code field.

/* Servo motor with potentiometer and Arduino example code. More info: https://www.makerguides.com/ */ #include <Servo.h> // include the required Arduino library #define servoPin 9 // Arduino pin for the servo #define potPin A0 // Arduino pin for the potentiometer int angle = 0; // variable to store the servo position in degrees int reading = 0; // variable to store the reading from the analog input Servo myservo; // create a new object of the servo class void setup() { myservo.attach(servoPin); } void loop() { reading = analogRead(potPin); // read the analog input angle = map(reading, 0, 1023, 0, 180); // map the input to a value between 0 and 180 degrees myservo.write(angle); // tell the servo to go to the set position delay(15); // wait 15 ms for the servo to reach the position }

Notice that before the setup and loop section of the code a new variable is added and the potentiometer input pin is defined.

In the loop section of the code, we read the value from the analog pin A0 with the function .

reading = analogRead(potPin); // read the analog input

Arduino boards contain a 10-bit analog to digital converter (ADC), so this gives us a value between 0 and 1023 depending on the position of the potentiometer.

Because the servo motor can only rotate between 0 and 180 degrees, we need to scale the values down with the map() function. This function re-maps a number from one range to another.

angle = map(reading, 0, 1023, 0, 180); // map the input to a value between 0 and 180 degrees

Lastly, we write the angle to the servo motor:

myservo.write(angle); // tell the servo to go to the set position delay(15); // wait 15 ms for the servo to reach the position

Controlling multiple servo motors

Controlling multiple servos is just as easy as controlling only one but I often get questions about how to modify the code. Therefore, I have added a simple example below.

how-to-control-multiple-servo-motors-with-arduino-wiring-diagram-schematic-circuit-tutorial-1

Note that you will have to use an external power supply to power the servos because the Arduino can not provide enough current to power all of the motors.

For this example, we just use more Arduino pins for the additional servos. However, this means that you are limited to 12 servos when using an Arduino Uno, and you might not have enough pins left over for other components.

Another option is to use one or multiple PCA9685 PWM/servo drivers. This driver allows you to control 16 servos with just 2 pins from the Arduino by using I2C. Adafruit also sells these in the form of an Arduino shield.

Because the setup of these servo drivers is a bit more difficult, I will cover this in a separate tutorial.


Arduino with multiple servos example code

As you can see in the example below, you just have to create more objects of the Servo class with different names. You can address each servo by using the correct name in the setup and loop section of the code.

/* Arduino with multiple servos example code. More info: https://www.makerguides.com/ */ #include <Servo.h> Servo servo1; Servo servo2; Servo servo3; Servo servo4; Servo servo5; void setup() { servo1.attach(9); servo2.attach(10); servo3.attach(11); servo4.attach(12); servo5.attach(13); } void loop() { servo1.write(0); servo2.write(0); servo3.write(0); servo4.write(0); servo5.write(0); delay(2000); servo1.write(90); servo2.write(90); servo3.write(90); servo4.write(90); servo5.write(90); delay(1000); servo1.write(180); servo2.write(180); servo3.write(180); servo4.write(180); servo5.write(180); delay(1000); }

Servo motor specifications

Below you can find the specifications of some of the most popular servo motors on the market. The original manufacturer of these servo motors is Tower Pro Pte Ltd. but similar models can be purchased from many other suppliers as well.

SG90 analog micro servo

Specifications

Operating voltage4.8 V
Weight9 g
Stall torque1.8 kg/cm (4.8 V)
Gear typePOM gear set
Operating speed0.12 sec/60° (4.8 V)
Operating temperature0 – 55 °C
CostCheck price

Dimensions


MG90S digital micro servo

Specifications

Operating voltage4.8 V
Weight13.4 g
Stall torque1.8 kg/cm (4.8 V), 2.2 kg/cm (6.6 V)
Gear type6061-T6 aluminum
Operating speed0.10 sec/60° (4.8 V), 0.08 sec/60° (6.0 V)
Operating temperature0 – 55 °C
CostCheck price

Dimensions


MG996R high torque digital servo

Specifications

Operating voltage4.8 – 6.6 V
Current draw at idle10 mA
No-load operating current draw170 mA
Stall current draw1400 mA
Weight55 g
Stall torque9.4 kg/cm (4.8 V), 11 kg/cm (6.0 V)
Gear typeMetal gear
Operating speed0.19 sec/60° (4.8 V), 0.15 sec/60° (6.0 V)
Operating temperature0 – 55 °C
CostCheck price

Dimensions


Conclusion

In this tutorial, I have shown you how to use servo motors with Arduino. We looked at the basics of controlling the position and speed of servo motors, how to control a servo motor with a potentiometer, and how to control multiple servo motors at the same time.

I hope you found this article useful and informative. If you did, please share it with a friend who also likes electronics and making things!

I would love to know what project you plan on building or have already built with servo motors and the Arduino. If you have any questions, suggestions, or if you think that things are missing in this tutorial, please leave a comment below.

Note that comments are held for moderation to prevent spam.

Creative Commons License
Sours: https://www.makerguides.com/servo-arduino-tutorial/
Multiple Servo Motor Control with Joystick and Arduino

Servo

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

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.

Examples

  • Knob: control the shaft of a servo motor by turning a potentiometer
  • Sweep: sweeps the shaft of a servo motor back and forth

Methods

Sours: https://www.arduino.cc/reference/en/libraries/servo/

You will also like:

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

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.

Examples

  • Knob: Control the position of a servo with a potentiometer.
  • Sweep: Sweep the shaft of a servo motor back and forth.


Last revision 2019/12/24 by SM

Functions

Examples

  • Knob: control the shaft of a servo motor by turning a potentiometer.
  • Sweep : sweeps the shaft of a servo motor back and forth.
Sours: https://www.arduino.cc/en/Reference/Servo"


1447 1448 1449 1450 1451