Using Raspberry Pi to Control Servo Motors in Automated Packaging and Labeling Systems
When it comes to building affordable, scalable automation solutions, few combinations are as powerful and accessible as pairing a Raspberry Pi with micro servo motors. In the world of automated packaging and labeling, where precision, speed, and repeatability are non-negotiable, the micro servo motor has emerged as a silent workhorse. This article dives deep into how you can leverage Raspberry Pi to control these tiny but mighty actuators for real-world packaging and labeling tasks—from pick-and-place mechanisms to label applicators and conveyor diverters.
Why Micro Servo Motors Are a Perfect Fit for Packaging Automation
Before we get into the wiring and code, let’s talk about why micro servo motors are so well-suited for this domain. Unlike larger industrial servos that require complex drivers and high-voltage power supplies, micro servo motors—like the popular SG90 or MG90S—operate on 5V DC and communicate via a simple PWM (Pulse Width Modulation) signal. This makes them directly compatible with the GPIO pins on a Raspberry Pi without needing an external motor controller in many cases.
Key Characteristics That Matter in Packaging
- Small form factor: Micro servos can fit into tight spaces inside labeling heads or packaging arms.
- High torque-to-weight ratio: Despite their size, models like the MG90S deliver up to 1.8 kg·cm of torque—enough to actuate lightweight labeling mechanisms or small flaps.
- Positional accuracy: With a typical 90° to 180° range of motion and a dead-band width of around 1–2 microseconds, micro servos can reliably hit repeatable positions, essential for consistent label placement.
- Low cost: At under $5 per unit, you can build multi-axis systems without breaking the bank.
Hardware Setup: Connecting a Micro Servo to Raspberry Pi
Let’s walk through a typical wiring scenario. You’ll need:
- A Raspberry Pi (any model with GPIO pins works; Pi 3B+, Pi 4, or Pi 5 are ideal)
- A micro servo motor (SG90 or MG90S)
- A 5V external power supply (do not draw servo current from the Pi’s 5V rail—trust me, you’ll brown out the system)
- A 470 µF electrolytic capacitor (optional but recommended to smooth voltage spikes)
- Jumper wires (female-to-female for the servo connector)
Wiring Diagram
| Servo Wire | Connection | |------------|------------| | Brown (GND) | Common ground with Pi and external supply | | Red (VCC) | 5V from external power supply | | Orange (Signal) | GPIO 18 (PWM0) on Raspberry Pi |
Critical note: Connect the ground of the external power supply to the ground of the Raspberry Pi. Without a common ground, the PWM signal will be floating and the servo will behave erratically.
Power Considerations
A single micro servo can draw up to 500 mA under stall load. If you’re running two or three servos simultaneously, use a 5V 2A or higher supply. The Pi itself can be powered separately or through the same supply if it’s rated for at least 3A total. A common setup is to use a 5V 3A adapter that feeds both the Pi (via USB-C or GPIO 5V pin) and the servos (via a breadboard power rail).
Software Foundation: PWM Control on Raspberry Pi
The Raspberry Pi has two hardware PWM channels, but GPIO 18 is the most commonly used for servo control because it’s connected to PWM0 on the BCM2835 chip. However, software-based PWM via libraries like pigpio or RPi.GPIO is more flexible and supports multiple servos.
Installing Required Libraries
bash sudo apt update sudo apt install python3-pip sudo pip3 install pigpio sudo systemctl enable pigpiod sudo systemctl start pigpiod
The pigpio library runs a daemon that provides accurate hardware-timed PWM, which is crucial for smooth servo motion.
Basic Servo Sweep Script
Here’s a minimal Python script to test your setup:
python import pigpio import time
SERVO_GPIO = 18 pi = pigpio.pi()
Set PWM frequency to 50 Hz (standard for servos)
pi.setPWMfrequency(SERVO_GPIO, 50)
Sweep from 0° to 180° and back
while True: # 0° typically corresponds to 500-600 µs pulse width pi.setservopulsewidth(SERVOGPIO, 500) time.sleep(1) # 90° is around 1500 µs pi.setservopulsewidth(SERVOGPIO, 1500) time.sleep(1) # 180° is around 2500 µs pi.setservopulsewidth(SERVO_GPIO, 2500) time.sleep(1)
Important calibration note: Not all micro servos use the same pulse width range. Some SG90 variants operate between 600 µs and 2400 µs, while others might use 500–2500 µs. Always test your specific servo by slowly increasing the pulse width and listening for mechanical binding.
Building a Label Applicator Arm with a Micro Servo
Now let’s apply this to a real packaging scenario: a label applicator arm that swings a vacuum pickup nozzle or a tamp pad onto a passing product.
Mechanical Design Considerations
- Lever arm length: Keep it under 5 cm to avoid exceeding the servo’s torque rating. A longer arm increases leverage but reduces the force available at the tip.
- Return spring: For fail-safe operation, add a light spring that returns the arm to the home position if power is lost.
- Mounting: Use a metal bracket for the servo; plastic can flex under repetitive loads.
Code for a Triggered Label Application
Assume a sensor (e.g., an infrared break-beam sensor) triggers the label cycle when a product arrives.
python import pigpio import time import RPi.GPIO as GPIO
SERVOPIN = 18 SENSORPIN = 17
pi = pigpio.pi() GPIO.setmode(GPIO.BCM) GPIO.setup(SENSORPIN, GPIO.IN, pullupdown=GPIO.PUDUP)
def applylabel(): # Swing arm from home (0°) to apply position (90°) pi.setservopulsewidth(SERVOPIN, 600) # home time.sleep(0.3) pi.setservopulsewidth(SERVOPIN, 1500) # apply time.sleep(0.5) # dwell time for label transfer pi.setservopulsewidth(SERVOPIN, 600) # return home time.sleep(0.3)
try: while True: if GPIO.input(SENSORPIN) == GPIO.LOW: applylabel() time.sleep(0.2) # debounce delay except KeyboardInterrupt: pi.stop() GPIO.cleanup()
Performance tip: The dwell time at the apply position (0.5 seconds in this example) can be tuned based on your label adhesive tack and product speed. For high-speed lines, reduce this to 100–200 ms and use a faster servo like the MG90S.
Multi-Servo Coordination for Pick-and-Place Packaging
A more advanced system might use two or three micro servos to form a simple pick-and-place robot. For example, one servo controls a rotating turret, another lifts a vacuum head, and a third actuates the gripper.
Synchronization Using Threading
Running multiple servos sequentially can cause delays. Instead, use Python threading or the pigpio callback system to move servos simultaneously.
python import pigpio import threading import time
pi = pigpio.pi()
servo1pin = 18 servo2pin = 19
def moveservo(servopin, targetpulse, duration): pi.setservopulsewidth(servopin, target_pulse) time.sleep(duration)
Move both servos at the same time
t1 = threading.Thread(target=moveservo, args=(servo1pin, 1500, 1.0)) t2 = threading.Thread(target=moveservo, args=(servo2pin, 2000, 1.0)) t1.start() t2.start() t1.join() t2.join()
Calibration for Repeatable Packaging Positions
In packaging, repeatability is more important than absolute accuracy. Use a calibration routine where you manually set the pulse width for each required position (e.g., “pick,” “place,” “home”) and store them in a dictionary or JSON file.
python calibration = { "home": 600, "pick": 1200, "place": 2000, "eject": 2400 }
def gotoposition(positionname): pulse = calibration.get(positionname) if pulse: pi.setservopulsewidth(SERVO_PIN, pulse) time.sleep(0.5)
Integrating with a Conveyor System
No packaging line is complete without a conveyor. A micro servo can also act as a diverter gate or a stop gate.
Conveyor Gate Control Logic
- Gate closed: Servo at 0°, blocking product flow.
- Gate open: Servo at 90°, allowing product to pass.
- Gate divert: Servo at 180°, directing product to an alternate lane.
python def set_gate(state): if state == "closed": pi.set_servo_pulsewidth(GATE_PIN, 600) # 0° elif state == "open": pi.set_servo_pulsewidth(GATE_PIN, 1500) # 90° elif state == "divert": pi.set_servo_pulsewidth(GATE_PIN, 2400) # 180°
For high-speed diverting, consider using a continuous rotation servo (modified or dedicated) for faster response, but be aware that continuous rotation servos sacrifice positional control for speed.
Dealing with Common Issues in Micro Servo Systems
Jitter and Instability
If your micro servo jitters or oscillates around the target position, the most common causes are:
- Insufficient power supply: Use a separate 5V supply for the servos, not the Pi’s 5V rail.
- Noise on the signal line: Add a 100 nF capacitor between the signal pin and ground, close to the servo connector.
- Incorrect PWM frequency: Ensure it’s exactly 50 Hz. Some libraries default to 100 Hz, which causes continuous buzzing.
Overheating
Micro servos can overheat if stalled or driven continuously. In packaging applications, they typically move intermittently, so this is less of an issue. However, if your duty cycle is high (e.g., constant back-and-forth motion), add a heatsink or use a metal-geared servo like the MG90S.
Position Drift Over Time
If the servo slowly drifts from its commanded position, check for:
- Loose potentiometer wiper inside the servo (common in cheap units)
- Worn gears
- Insufficient pulse width refresh rate (send a refresh pulse every 20 ms even when holding position)
Scaling Up: From Prototype to Production
The beauty of using Raspberry Pi with micro servos is that you can prototype a packaging automation solution in a day for under $50, then scale it up to multiple stations.
Adding a Web Interface for Control
You can run a Flask web server on the Pi to control servos remotely—useful for manually overriding the system during setup or troubleshooting.
python from flask import Flask, request import pigpio
app = Flask(name) pi = pigpio.pi() SERVO_PIN = 18
@app.route('/move', methods=['POST']) def move(): angle = request.json.get('angle') pulse = 600 + (angle / 180.0) * 1800 # linear mapping pi.setservopulsewidth(SERVO_PIN, pulse) return f"Moved to {angle}°"
if name == 'main': app.run(host='0.0.0.0', port=5000)
Using a Servo Driver Board for More Channels
If you need more than two servos, consider the PCA9685 PWM driver board. It communicates via I2C and can control up to 16 servos independently with 12-bit resolution.
python from adafruit_servokit import ServoKit kit = ServoKit(channels=16) kit.servo[0].angle = 90 kit.servo[1].angle = 45
The PCA9685 offloads the PWM generation from the Pi, freeing up CPU cycles for vision processing or data logging.
Real-World Example: A Micro Servo-Controlled Label Rewinder
Let’s look at a specific application: a label rewinder that maintains constant tension on a roll of labels. A micro servo controls a friction brake arm that presses against the label roll.
- Sensor: A lever-arm microswitch detects when the label web is slack.
- Servo action: When slack is detected, the servo releases the brake (moves to 0°). When tension is restored, the servo applies the brake (moves to 45°).
- Tuning: The brake force is adjusted by changing the servo angle—more angle equals more pressure.
This is a classic closed-loop tension control system, implemented with nothing more than a $4 servo and a $2 switch.
Performance Benchmarks: What to Expect
Based on real-world testing with an MG90S servo on a Raspberry Pi 4:
| Parameter | Value | |-----------|-------| | Maximum speed (no load) | 0.10 sec/60° | | Repeatability | ±0.5° | | Maximum torque | 1.8 kg·cm | | Continuous duty cycle | 20% (intermittent) | | PWM update rate | 50 Hz (20 ms period) |
For a label applicator arm moving 90°, the total cycle time is approximately 150 ms (move) + 50 ms (settle) + 200 ms (dwell) = 400 ms. This translates to about 150 labels per minute—sufficient for many small-to-medium packaging lines.
Final Tips for Reliable Operation
- Always calibrate each servo individually before integrating into the system. Write a calibration script that prints the pulse width as you manually rotate the servo to find the mechanical limits.
- Use shielded twisted-pair wire for the signal line if your system has electrical noise from motors or relays.
- Add a mechanical stop to prevent the servo from exceeding its physical range. Even with software limits, a bug could cause the servo to jam and strip its gears.
- Log servo positions and sensor events to a CSV file for debugging and optimization. The Pi’s SD card is cheap storage—use it.
The combination of Raspberry Pi and micro servo motors democratizes packaging automation. You no longer need a $10,000 PLC and industrial servo drives to automate a labeling station or a small pick-and-place cell. With a few lines of Python and some off-the-shelf hardware, you can build a system that matches the reliability of commercial equipment at a fraction of the cost. And when your production needs grow, the same Pi can be networked into a larger Industry 4.0 framework, reporting servo positions, cycle counts, and fault conditions to a central dashboard. The only limit is how creatively you can apply that tiny, 9-gram servo.
Copyright Statement:
Author: Micro Servo Motor
Source: Micro Servo Motor
The copyright of this article belongs to the author. Reproduction is not allowed without permission.
Recommended Blog
- How to Control Servo Motors Using Raspberry Pi and the pigpio Library for Precision Robotics
- Implementing Servo Motors in Raspberry Pi-Based Automated Sorting and Packaging Systems
- Creating a Servo-Controlled Automated Trash Can Lid with Raspberry Pi
- How to Use Raspberry Pi to Control Servo Motors in Automated Assembly Lines
- Implementing Servo Motors in Raspberry Pi-Based Automated Sorting and Packaging Systems
- Implementing Servo Motors in Raspberry Pi-Based Automated Sorting Lines
- Building a Servo-Powered Automated Sorting Robot with Raspberry Pi and Sensors
- Integrating Multiple Servo Motors with Raspberry Pi
- Implementing Servo Motors in Raspberry Pi-Based Automated Warehouse Systems
- How to Control Servo Motors Using Raspberry Pi and the ServoBlaster Library
About Us
- Lucas Bennett
- Welcome to my blog!
Hot Blog
- How to Replace and Upgrade Your RC Car's Tires
- Micro Servo Motor Sizing for Drone Payload Manipulators
- What Happens Inside a Micro Servo Motor When It Moves?
- The Impact of 5G Technology on Micro Servo Motor Performance
- PWM in Communication Systems: Encoding Information
- Micro Servo Motor Control Signals: How They Drive Motion
- Micro Servos for Articulated Robot Arms vs Fixed Mounts
- Understanding the Thermal Conductivity of Motor Materials
- How to Build a Remote-Controlled Car with a Digital Proportional System
- Torque vs Speed Trade-Off in Different Micro Servo Types
Latest Blog
- Using Raspberry Pi to Control Servo Motors in Automated Packaging and Labeling Systems
- Specification of Connector Types (JR, Futaba, Molex etc.)
- How to Build a Remote-Controlled Car with a 3D-Printed Chassis
- Designing a Micro Servo Robotic Arm for Laboratory Automation
- How to Implement PWM in Arduino Projects
- The Impact of Gear Materials on Servo Motor Heat Generation
- How to Repair and Maintain Your RC Car's ESC Capacitor
- DIY Servo-Powered Blinds: Step-by-Step Guide
- The Use of Micro Servo Motors in Drones: Applications and Advancements
- PWM Control in Power Distribution Systems
- How Gear Teeth Design Influences Servo Motor Operation
- Micro Servo Motors in Automated Material Handling Systems
- Vector's Micro Servo Motors: Compact and Lightweight for Pan-Tilt Systems
- Specification of “Creeping” or Non-Holding Torque when Power Removed
- The Application of Micro Servo Motors in Robotics
- The Role of Micro Servo Motors in the Development of Smart Technological Systems
- Advances in Lubrication Systems for Micro Servo Motors
- Advances in Acoustic Management for Micro Servo Motors
- Micro Servo Motors in Automated Welding Systems
- The Best Micro Servo Motors for Arduino Projects: Brand Recommendations