Robotic Muscles: Master Arduino Servo Motors (SG90) for Precision Movement

Robotic Muscles: Master Arduino Servo Motors (SG90) for Precision Movement


📑Table of Contents
What You'll Need 5 items
Arduino Uno R3
Buy
SG90 Micro Servo
Buy
Breadboard
Buy
Jumper Wires
Buy
Capacitor (470uF)
Buy

Affiliate links help support this site at no extra cost to you.

Welcome to Day 22. Yesterday, we gave our robot Eyes (Ultrasonic Sensors). Today, we give it Muscles. But not just any muscles. We don’t want the dumb, spinning muscles of the DC Motor (Day 17). We want Smart Muscles. We want muscles that can move to exactly 90 degrees and hold that position against gravity. We want the Servo Motor.

This is the cornerstone of every robotic arm, walking hexapod, and camera gimbal you have ever seen. To master it, we must leave the world of simple High/Low signals and enter the world of Closed Loop Control.

Precision Control Close-up

The Anatomy: What is a Servo?

An SG90 Micro Servo looks like a tiny blue box. But inside, it is a marvel of engineering. It interacts with 4 distinct components packed into that tiny shell:

  1. DC Motor: A tiny high-speed motor (just like Day 17).
  2. Gear Train: A set of plastic or metal gears to slow the motor down and increase torque (Force).
  3. Potentiometer: A variable resistor attached to the output shaft. It measures the current angle of the arm.
  4. Control Circuit (PCB): The brain. It compares where the arm is (from the pot) vs where you want it to be (from the signal).

Internal Cutaway of SG90

The Feedback Loop (The “Closed Loop”)

This is the magic. When you tell a servo to go to 90 degrees:

  1. The PCB checks the Potentiometer: “Current Angle is 0”.
  2. The PCB powers the Motor: “Turn Right!”
  3. The Motor spins the gears. The arm moves. The Potentiometer turns.
  4. The PCB checks again: “Current Angle is 45… Keep going”.
  5. The PCB checks: “Current Angle is 90”.
  6. The PCB cuts power to the motor. “Stop”.
  7. The Deadband: The PCB usually stops the motor when it is “close enough” (within 3 microseconds). This prevents the motor from twitching endlessly between 89.9 and 90.1 degrees. This safety zone is called the Deadband.

Advanced Physics: PID Control

The brain inside the SG90 is actually a tiny analog computer running a P-Controller (Proportional Controller).

  • Error = Target - Current Position.
  • Motor Speed = Error * Kp (Gain). If the Error is big (Target 180, Current 0), the Motor Speed is MAX. As the arm gets closer (Error shrinks), the Motor Speed slows down. This creates a smooth arrival at the target instead of slamming into it. Expensive digital servos use PID (Proportional Integral Derivative) to predict momentum and stop on a dime. Cheap analog servos just use P, which is why they sometimes overshoot.

If you try to force the arm back to 0 with your hand, the Potentiometer moves. The PCB notices: “Hey! I should be at 90, but I am at 80!” It powers the motor to push back against your hand. This is called Holding Torque. It fights you to stay in position.

Deep Dive: Inside the Hardware (The H-Bridge)

How does the servo reverse direction? Does it use a relay? No. It uses a tiny H-Bridge circuit inside the chip (refer to Day 17). By rapidly switching four internal transistors, it can reverse the polarity of the DC motor instantly.

  • To go Left: Top-Left and Bottom-Right transistors open.
  • To go Right: Top-Right and Bottom-Left transistors open.
  • To Stop: All transistors close (or brake). Because this happens thousands of times a second, the motor can make micro-adjustments to hold the angle steady. This constant high-speed switching is why servos sometimes make a “buzzing” or “singing” sound even when standing still. They are actively fighting gravity.

Wiring: The standard 3-Wire Interface

Servos always have 3 wires. The colors are standardized (usually).

  • Brown: Ground (GND).
  • Red: Power (5V).
  • Orange: Signal (PWM).

Warning: Never plug the connector in backwards. It usually won’t break it instantly, but it won’t work. Double Warning: Never feed a servo more than 6V. It will fry the internal PCB. 5V is perfect.

SG90 Wire Pinout

The Code: The Servo Library

Controlling a servo manually is hard (we will see why in the Deep Dive). Luckily, Arduino has a built-in library that does the heavy lifting. #include <Servo.h>

The Basic Knob Sketch

Let’s connect a Potentiometer (Day 14) and use it to control the Servo angle. Wiring:

  1. Serum Red -> 5V.
  2. Serum Brown -> GND.
  3. Serum Orange -> Pin 9.
  4. Pot Left -> 5V.
  5. Pot Right -> GND.
  6. Pot Middle -> A0.

The Code:

#include <Servo.h>

Servo myServo;  // Create a servo object

void setup() {
  myServo.attach(9); // Tell Arduino the servo is on Pin 9
}

void loop() {
  int potValue = analogRead(A0); // Read Pot (0 to 1023)
  
  // Map the value to an angle (0 to 180)
  int angle = map(potValue, 0, 1023, 0, 180);
  
  myServo.write(angle); // Tell servo to go to that position
  delay(15); // Wait for the servo to get there
}

Upload this. Turn the knob. The motor mimics your movement perfectly. Congratulations, you just built a Remote Manipulator.

Breadboard Wiring: Servo + Knob

Understanding map()

Why did we use map()?

  • analogRead() gives us 0 to 1023.
  • myServo.write() expects 0 to 180. If you send myServo.write(500), the library will just clamp it to 180. We need to scale the numbers down proportionally. map(value, InLow, InHigh, OutLow, OutHigh) does accurately this math for us.

Visualization of Map Function

Deep Dive: The Signal (PWM vs Servo PPM)

Wait, didn’t we learn PWM on Day 15? We used analogWrite() to dim LEDs. That was 490Hz or 980Hz. Servo PWM is different. It runs at 50Hz (50 times a second). The period is 20ms. The angle is determined by the width of the HIGH pulse.

  • 1.0 ms HIGH: 0 Degrees (Rotate fully Left).
  • 1.5 ms HIGH: 90 Degrees (Center).
  • 2.0 ms HIGH: 180 Degrees (Rotate fully Right).

This is precise timing. If the wire is loose and the pulse stretches from 1.5ms to 1.6ms, the arm will jitter. This is why servos sometimes “twitch” if the connection is bad.

PWM Signal Timing Diagram

Advanced Code: writeMicroseconds()

The write(angle) function is easy, but it is “low resolution”. It only lets you move in 1-degree steps. What if you need to aim a laser at 90.5 degrees? Use myServo.writeMicroseconds(us). Instead of angles (0-180), you send the raw time (1000 to 2000).

  • myServo.write(90) is the same as myServo.writeMicroseconds(1500).
  • myServo.write(91) is roughly myServo.writeMicroseconds(1511). But you can type myServo.writeMicroseconds(1505)! This gives you 10x more precision. For robotic arms, always use microseconds. For waving a flag, use degrees.

History: From RC Planes to Robots

Why is the standard 50Hz? Why 1ms to 2ms? It comes from Model Aviation in the 1960s. Radio Control (RC) planes needed a way to control flaps and rudders wirelessly. The analog radios of the time found it easy to send a “Pulse Train” where the width of the pulse represented the stick position. The components chosen for the receiver decoders (decades before Arduinos existed) just happened to work best with a 20ms refresh rate. The entire robotics industry today causes this 60-year-old standard invented by hobbyists flying balsa wood planes. It is a legacy standard, but it is so robust that it refuses to die.

Comparison: Servo vs Stepper vs DC Motor

Beginners often ask: “Which motor should I use?” Let’s settle this once and for all.

  1. DC Motor (Day 17):
    • Pro: Fast, Strong, Simple.
    • Con: Dumb. No position control. You don’t know where it is.
    • Use for: Wheels, Fans, Drills.
  2. Servo Motor (Day 22):
    • Pro: Precise Angle (0-180). Smart. High Torque.
    • Con: Limited range (usually can’t spin 360). Slower rpm.
    • Use for: Robot Arms, Steering, Grippers, Gimbals.
  3. Stepper Motor (Phase 5):
    • Pro: Precise Rotation (infinite spin). Extremely accurate control of speed and distance.
    • Con: Complex driver needed. Low efficiency.
    • Use for: 3D Printers, CNC Machines.

Troubleshooting: The Jitter and The Brownout

The #1 problem beginners face with Servos: The Arduino Resets. You move the motor, and the Arduino reboots. Why? Power Starvation. When a servo starts moving, it draws a massive spike of current (Inrush Current). Sometimes it draws 500mA or more. If the USB port cannot supply enough juice, the 5V rail voltage dips down to 3.5V. The Arduino’s brain needs 4.5V to think. It blacks out (Brownout) and resets.

Oscilloscope Trace of Brownout

The Fix: The Decoupling Capacitor

We need a backup battery tank. We place a large Electrolytic Capacitor (470uF or 1000uF) across the power rails (+ and -) near the servo. When the servo demands a spike of power, the capacitor dumps its stored energy to fill the gap. It smooths out the voltage dips and keeps the Arduino alive. Rule: If you use more than 2 servos, ALWAYS use an external 5V power supply (like 4xAA batteries). Do not power them from the Arduino 5V and USB.

Schematic: Capacitor Placement

Troubleshooting: The “Singing” Servo

Sometimes, your servo will sit at 90 degrees and make a high-pitched whine. eeeeeeeeeeeeee This happens when the physical arm is almost at the target, but not quite. Maybe gravity is pulling it down by 0.1 degrees. The Feedback loop fights back: “Go Up!” Gravity pulls: “Go Down!” It oscillates at high speed. The Fix:

  1. Remove Load: The arm might be too heavy. Counter-balance it.
  2. Turn it off: If the robot is idle, myServo.detach() to stop the signal. The motor will relax (and the whine stops).
  3. Digital vs Analog: Analog servos (like SG90) whine less but are less precise. Digital servos are precise but whine more.

Safety: Current Limiting (Don’t Stall!)

What happens if you tell the servo to go to 180, but you block it with your hand? The PCB sees “Error” -> “Full Power!” The motor draws Stall Current (often 1 Amp for a tiny SG90).

  • The H-Bridge warms up.
  • The Motor coils warm up.
  • The plastic case melts. Never stall a servo for more than a few seconds. It will destroy itself. If your code sees that position is not changing even though you are telling it to move, you should program an “Emergency Stop”.

Project Ideas

Now that you have motion, what can you build?

1. The Useless Box

This is a classic internet meme project. A box with a switch. When you flip the switch ON… A servo arm pops out of the box… …and flips the switch OFF. Then it goes back inside. It is a machine with the sole purpose of turning itself off. It requires: 1 Servo, 1 Switch, and some cardboard engineering.

Useless Box Concept

2. The Hexapod

Using 3 servos per leg, and 6 legs… you need 18 servos. You can make a spider that walks over rough terrain. This requires a dedicated Servo Driver Board (like the PCA9685) because the Arduino Uno doesn’t have enough pins. We will cover I2C Servo Drivers in Phase 5.

Hexapod Robot Concept

3. The Pan-Tilt Camera Mount

This is the “Hello World” of 2-axis control. You mount one servo horizontally (Pan) and glue a second servo on top of it vertically (Tilt). Now you have a turret.

  • Pan: 0-180 (Left/Right).
  • Tilt: 0-180 (Up/Down). If you attach a specific stick (Joystick), you can control looking around. Code Tip: You need TWO servo objects.
Servo panServo;
Servo tiltServo;
void setup() {
  panServo.attach(9);
  tiltServo.attach(10);
}

4. The Robotic Claw (Gripper)

Every arm needs a hand. A “Parallel Gripper” uses a single servo to open and close two jaws.

  • 0 Degrees: Jaws Fully Open.
  • 180 Degrees: Jaws Fully Closed. Pro Tip: Do not drive the servo all the way to 180 if the object is large. If you grab a soda can and the servo tries to go to 180 (where the jaws would touch), it will stall and burn out. detect the “squeeze” by reading the current (advanced) or just utilize a “Soft Touch” approach where you increment the angle slowly until you are sure you have gripped the object.

5. Mechanical Safety: The Horn and Spline

The white plastic arm that snaps onto the motor is called the Horn. The jagged metal/plastic shaft it connects to is the Spline. Crucial Advice:

  1. Count the teeth: Different brands (Futaba, Hitec, TowerPro) have different tooth counts (23T, 24T, 25T). They are not compatible. Don’t force a horn onto the wrong spline.
  2. The Center Screw: Always install the tiny screw in the center. Without it, the horn will pop off when the robot tries to lift something heavy.
  3. Zeroing: Before you screw the horn on, run code to move the servo to 90 degrees. Then attach the horn pointing straight up. This ensures your robot is mechanically aligned with your code.

Science Class: Torque and Leverage

Why are robot arms always short? Because of Torque. The SG90 is rated for 1.8 kg-cm. This means:

  • At 1 cm from the center, it can lift 1.8 kg.
  • At 2 cm from the center, it can lift 0.9 kg.
  • At 10 cm from the center, it can lift 0.18 kg (180 grams). The Law of the Lever: Torque=Force×DistanceTorque = Force \times Distance. If you make your robot arm twice as long, it becomes half as strong. Engineering Rule: Keep the heavy motors near the “shoulder” (base). Keep the “hand” light. This minimizes the lever arm and maximizes lifting capacity. This is why industrial robots look the way they do.

Hacker’s Corner: Controlling Speed

The standard Servo library moves at maximum speed. myServo.write(180) teleports the arm as fast as physics allow. What if you want a slow, cinematic move? You have to write a for loop with delays.

// Slowly move from 0 to 180
for (int pos = 0; pos <= 180; pos += 1) { 
  myServo.write(pos);
  delay(15); // Adjust this delay to change speed
}

If you hate writing loops, install the VarSpeedServo library. It lets you do: myServo.write(180, 30); (Angle 180, Speed 30). It handles the timing in the background (using Interrupts), so your code doesn’t freeze!

Deep Dive: Continuous Rotation Servos

Sometimes you buy a servo that looks like an SG90, but it spins 360 degrees forever. This is a Continuous Rotation Servo. It is NOT a normal servo. It is a DC Motor with a brain transplant. The manufacturer has:

  1. Removed the physical stopper from the gear.
  2. Replaced the Potentiometer with two fixed resistors (tricking the brain into thinking it is ALWAYS at 90 degrees). How to control it:
  • write(90): Stop. (Brain thinks it’s at the target).
  • write(180): Full Speed Forward. (Brain thinks “I’m at 90, I need to get to 180, Go Fast!”).
  • write(0): Full Speed Backward. You lose Position Control, but you gain a high-torque geared motor that needs no driver shield. Perfect for wheels on a small robot.

The Engineer’s Glossary (Day 22)

  • Actuator: A component that is responsible for moving and controlling a mechanism.
  • Torque: Rotational force. Measured in kg-cm. An SG90 has 1.8 kg-cm torque (it can lift 1.8kg if the arm is 1cm long).
  • Closed Loop: A system that monitors its output and adjusts its input to minimize error.
  • PWM (Pulse Width Modulation): Encoded signal where the width of the pulse carries the information (Angle).
  • Deadband: The small range of signal near the target where the servo rests to prevent oscillation.
  • Sweep: Creating code that moves the servo back and forth automatically (for loop).

Conclusion

You have mastered the muscle. You understand that a servo is not just a motor; it is a smart feedback system. You know how to control it, and more importantly, how to power it safely without crashing your brain.

We have Eyes (Day 21). We have Muscles (Day 22). Tomorrow, Day 23, is special. We are going to combine everything. We are going to verify our skills with a Capstone Project. We will build a Radar Station that sweeps the area and displays targets on a screen. It will combine Ultrasonic, Servo, and Serial Communication.

Get your jumper wires ready. See you on Day 23.

Comments