Creating a Servo-Controlled Automated Trash Can Lid with Raspberry Pi
If you’ve ever walked into a kitchen with your hands full of dirty dishes and had to awkwardly nudge a trash can lid open with your knee, you know the pain. The solution? An automated trash can lid that opens with a wave of your hand—or better yet, a tap on your phone. This project combines the humble micro servo motor with the versatility of a Raspberry Pi to create a smart, responsive lid that feels like something straight out of a sci-fi kitchen.
In this guide, I’ll walk you through the entire process—from selecting the right micro servo motor to wiring, coding, and even adding a proximity sensor for touchless operation. By the end, you’ll have a fully functional prototype that you can customize further. Let’s dive in.
Why a Micro Servo Motor is the Perfect Choice for This Project
Before we get into the build, let’s talk about the star of the show: the micro servo motor. You might be tempted to use a regular DC motor or a stepper motor, but for a trash can lid, the micro servo offers a unique set of advantages.
Precise Angular Control
A micro servo motor, like the popular SG90 or MG90S, is designed for precise angular positioning. Unlike a DC motor that spins continuously, a servo can be commanded to move to a specific angle—say 0°, 90°, or 180°. This is perfect for a trash can lid that needs to open to a fixed angle (e.g., 120°) and then close back to 0°. With a servo, you don’t need limit switches or complex feedback loops; the motor’s internal potentiometer and control electronics handle position feedback automatically.
Compact Size and Low Power
Micro servos are small—typically about 23 x 12 x 29 mm—and weigh only 9 to 14 grams. This makes them ideal for retrofitting onto a standard kitchen trash can without adding bulk. They also operate on 5V DC, which is directly compatible with the Raspberry Pi’s GPIO pins (though you’ll need an external power source for the motor itself, as the Pi’s 5V rail can only supply about 500mA).
Torque That’s Just Right
A typical micro servo like the SG90 delivers around 1.8 kg·cm of torque at 4.8V. That might not sound like much, but for a lightweight plastic or metal trash can lid (weighing maybe 200–500 grams), it’s more than sufficient. If your lid is heavier, you can step up to a metal-geared micro servo like the MG90S, which offers 2.2 kg·cm and is far more durable under repeated load.
Speed and Responsiveness
Micro servos are fast. A standard SG90 can rotate 60° in about 0.12 seconds at 4.8V. That means your trash can lid can go from closed to fully open in less than a quarter of a second—plenty fast for a natural, satisfying user experience.
Hardware Components: What You’ll Need
Let’s assemble the shopping list. I’ll assume you already have a Raspberry Pi (any model with GPIO headers works, but a Pi 3B+ or Pi 4 is recommended for ease of use). Here’s everything else:
- Micro servo motor: SG90 or MG90S (I recommend the MG90S for its metal gears and higher durability)
- Raspberry Pi: Any model with Wi-Fi (Pi 3B+, Pi 4, Pi Zero W)
- HC-SR04 ultrasonic sensor (for touchless wave detection) – optional but highly recommended
- 5V 2A power supply for the Raspberry Pi
- External 5V power supply for the servo (e.g., a 5V 2A wall adapter or a set of 4 AA batteries)
- Breadboard and jumper wires (female-to-female for Pi connections, male-to-female for sensor)
- 10µF capacitor (optional, to smooth servo power spikes)
- 1kΩ and 2kΩ resistors (for voltage divider if using 5V sensor with 3.3V Pi)
- Small trash can with a hinged lid – any standard kitchen bin works
- Mechanical mounting hardware: zip ties, small brackets, or 3D-printed servo mount
- Push button (optional, for manual override)
Wiring Diagram Overview
Here’s the basic wiring layout. Note that the servo’s signal pin (usually orange or white) connects to a GPIO pin on the Pi—I’ll use GPIO 18 (physical pin 12). The servo’s power (red) goes to the external 5V supply’s positive terminal, and ground (brown or black) connects to both the external supply’s ground and the Pi’s ground (to create a common reference).
For the HC-SR04 sensor: - VCC → Pi 5V (pin 2) - Trig → GPIO 23 (pin 16) - Echo → GPIO 24 (pin 18) – but use a voltage divider (1kΩ and 2kΩ) to step down the 5V echo signal to 3.3V safe for the Pi - GND → Pi ground (pin 6)
Step 1: Setting Up the Raspberry Pi Environment
First, ensure your Pi is running the latest Raspberry Pi OS (Bullseye or Bookworm). I’ll use Python with the RPi.GPIO library for simplicity.
Install Required Libraries
Open a terminal and run:
bash sudo apt update sudo apt install python3-pip pip3 install RPi.GPIO
If you’re using a Pi 5 (which has different GPIO hardware), you might need gpiozero instead. For this guide, I’ll stick with RPi.GPIO for broad compatibility.
Enable I2C and SPI (Not Required, But Good to Know)
For this project, we only use GPIO, so no need to enable I2C or SPI. But if you later add an OLED display or a PIR sensor, you might need them.
Step 2: Mounting the Micro Servo to the Trash Can Lid
This is the most mechanical part of the build. The goal is to attach the servo’s horn to the lid’s hinge or a lever arm that pushes the lid open.
Method A: Direct Hinge Mount (Best for Light Lids)
If your trash can lid has a simple hinge (like a flip-top bin), you can: 1. Remove the existing hinge pin (if possible) or drill a small hole in the lid’s hinge tab. 2. Attach a servo horn to the lid using a screw or a zip tie. 3. Mount the servo body to the trash can’s rim using a bracket or double-sided tape (reinforced with a zip tie for security).
The servo’s rotation axis should align with the lid’s hinge axis. When the servo rotates from 0° to 120°, the horn pushes the lid open.
Method B: Lever Arm (For Heavier Lids)
For heavier lids, use a lever arm: 1. Attach a rigid arm (e.g., a popsicle stick or 3D-printed part) to the servo horn. 2. Connect the other end of the arm to the lid’s edge via a small hinge or a ball joint. 3. Mount the servo on the side of the trash can, near the lid’s hinge.
When the servo rotates, the arm pushes the lid upward. This gives more mechanical advantage.
Pro tip: Use a metal-geared servo (MG90S) for any method. Plastic gears in an SG90 can strip under repeated load, especially if the lid sticks or is pushed down accidentally.
Step 3: Writing the Python Code for Servo Control
Now let’s make the servo move. Here’s a simple script that opens and closes the lid using a button press (or you can trigger it via a sensor later).
Basic Servo Test Script
Create a file called servo_test.py:
python import RPi.GPIO as GPIO import time
SERVO_PIN = 18
GPIO.setmode(GPIO.BCM) GPIO.setup(SERVO_PIN, GPIO.OUT)
Set PWM frequency to 50Hz (standard for servos)
pwm = GPIO.PWM(SERVO_PIN, 50) pwm.start(0)
def set_angle(angle): # Convert angle (0-180) to duty cycle (2-12.5 for most servos) duty = (angle / 18.0) + 2.5 pwm.ChangeDutyCycle(duty) time.sleep(0.5) # Give servo time to reach position pwm.ChangeDutyCycle(0) # Stop sending signal to avoid jitter
try: while True: cmd = input("Enter 'o' to open, 'c' to close, 'q' to quit: ") if cmd == 'o': setangle(120) # Open position print("Lid opened") elif cmd == 'c': setangle(0) # Closed position print("Lid closed") elif cmd == 'q': break finally: pwm.stop() GPIO.cleanup()
Run it with python3 servo_test.py. You should see the servo move to 120° when you type ‘o’ and back to 0° when you type ‘c’.
Note on duty cycle calibration: The values 2.5 and 12.5 are typical for an SG90. Your servo might need slight adjustments. If the servo doesn’t move to the expected angle, tweak the duty formula. For example, for 0°, try duty = 2.0; for 180°, try duty = 12.0.
Step 4: Adding Touchless Control with an Ultrasonic Sensor
A wave-activated lid is far more hygienic. Let’s integrate the HC-SR04 ultrasonic sensor.
How It Works
The sensor emits an ultrasonic pulse and measures the time it takes for the echo to return. By calculating the distance to an object (your hand), we can trigger the servo when something is within, say, 10 cm.
Wiring the HC-SR04
As mentioned earlier, the Echo pin outputs 5V, but the Pi’s GPIO pins are 3.3V tolerant. Use a voltage divider:
- Echo → 1kΩ resistor → GPIO 24
- Between GPIO 24 and ground, connect a 2kΩ resistor
This creates a 3.3V signal safe for the Pi.
Full Code with Sensor Integration
Create auto_trash.py:
python import RPi.GPIO as GPIO import time
Pin assignments
SERVOPIN = 18 TRIGPIN = 23 ECHO_PIN = 24
Setup GPIO
GPIO.setmode(GPIO.BCM) GPIO.setup(SERVOPIN, GPIO.OUT) GPIO.setup(TRIGPIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN)
Servo PWM
pwm = GPIO.PWM(SERVO_PIN, 50) pwm.start(0)
State variables
lidopen = False lasttrigger_time = 0 cooldown = 2 # seconds before allowing another open/close
def set_angle(angle): duty = (angle / 18.0) + 2.5 pwm.ChangeDutyCycle(duty) time.sleep(0.5) pwm.ChangeDutyCycle(0)
def getdistance(): # Send trigger pulse GPIO.output(TRIGPIN, False) time.sleep(0.000002) # 2 microseconds GPIO.output(TRIGPIN, True) time.sleep(0.00001) # 10 microseconds GPIO.output(TRIGPIN, False)
# Wait for echo start while GPIO.input(ECHO_PIN) == 0: pulse_start = time.time() # Wait for echo end while GPIO.input(ECHO_PIN) == 1: pulse_end = time.time() # Calculate distance in cm pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 # Speed of sound ~343 m/s distance = round(distance, 2) return distance try: print("Automated trash can lid running...") while True: dist = getdistance() currenttime = time.time()
if dist < 10 and dist > 2: # Hand within 2-10 cm if (current_time - last_trigger_time) > cooldown: if not lid_open: print(f"Hand detected at {dist} cm - Opening lid") set_angle(120) lid_open = True last_trigger_time = current_time else: print(f"Hand detected at {dist} cm - Closing lid") set_angle(0) lid_open = False last_trigger_time = current_time time.sleep(0.1) # Small delay to avoid excessive CPU usage except KeyboardInterrupt: print("\nShutting down...") finally: set_angle(0) # Close lid on exit pwm.stop() GPIO.cleanup()
Run this script, and wave your hand in front of the sensor. The lid should open. Wave again, and it closes.
Step 5: Fine-Tuning the Micro Servo Performance
You might notice the servo jitters or makes a buzzing sound when holding a position. This is normal for continuous PWM signals, but we can improve it.
Why Servos Buzz
The buzzing comes from the servo’s internal PID controller constantly trying to correct position. To reduce it, we stop sending the PWM signal after the servo reaches its target angle (as I did with pwm.ChangeDutyCycle(0) in the code). However, this means the servo loses holding torque. For a trash can lid, that’s fine—gravity will keep it closed, and the lid’s hinge friction will hold it open.
Dealing with Power Spikes
When a servo starts moving, it can draw up to 500mA for a split second. If you power the servo from the Pi’s 5V pin, you might cause the Pi to brown out and reboot. Always use an external 5V supply for the servo, and connect its ground to the Pi’s ground.
If you still see erratic behavior, add a 10µF capacitor between the servo’s power and ground pins (close to the servo) to smooth out voltage dips.
Step 6: Adding Remote Control via Wi-Fi (Optional Bonus)
Want to open the lid from your phone? Let’s add a simple Flask web server.
Install Flask
bash pip3 install flask
Create a Web Interface
Save this as web_trash.py:
python from flask import Flask, rendertemplatestring import RPi.GPIO as GPIO import time
app = Flask(name)
SERVOPIN = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(SERVOPIN, GPIO.OUT) pwm = GPIO.PWM(SERVO_PIN, 50) pwm.start(0)
def set_angle(angle): duty = (angle / 18.0) + 2.5 pwm.ChangeDutyCycle(duty) time.sleep(0.5) pwm.ChangeDutyCycle(0)
HTML = """
Smart Trash Can """
@app.route('/') def index(): return rendertemplatestring(HTML)
@app.route('/open') def openlid(): setangle(120) return "Lid opened"
@app.route('/close') def closelid(): setangle(0) return "Lid closed"
if name == 'main': app.run(host='0.0.0.0', port=5000)
Run it with sudo python3 web_trash.py. Access the Pi’s IP address on port 5000 from any device on your network. Tap the buttons to control the lid remotely.
Common Pitfalls and How to Avoid Them
Servo Not Moving
- Check wiring: Signal pin to GPIO, power to external 5V, ground common.
- Verify PWM frequency: 50Hz is standard. Some servos use 60Hz.
- Test with a simple script that sweeps from 0 to 180 to confirm the servo works.
Lid Opens Too Slowly or Not Fully
- Increase the sleep time after setting the angle to allow the servo to reach position.
- Check mechanical binding. The servo horn might be slipping on the shaft—tighten the screw.
- For heavy lids, use a lever arm with a longer moment arm to reduce required torque.
Sensor False Triggers
- The HC-SR04 can be fooled by reflections. Place it at least 5 cm away from the trash can’s edge.
- Add a software filter: require two consecutive readings under 10 cm before triggering.
Raspberry Pi Freezes
- This is almost always due to insufficient power. Use a quality 5V 2.5A supply for the Pi and a separate supply for the servo.
- Add a heatsink to the Pi’s CPU if running the web server continuously.
Taking It Further: Ideas for Expansion
You’ve built a functional automated trash can lid, but the possibilities are endless:
- Add a PIR motion sensor instead of ultrasonic for a broader detection zone.
- Integrate with Home Assistant using MQTT for voice control via Alexa or Google Home.
- Use a larger servo (like an MG996R) for industrial-sized bins.
- Add an OLED display showing lid status and battery level.
- Implement a sleep mode to save power when not in use—the servo draws no power when idle if you stop the PWM signal.
The micro servo motor is the unsung hero here. Its precision, small footprint, and ease of control make it the perfect actuator for this kind of IoT project. Whether you’re automating a trash can, a cat feeder, or a camera rig, the principles remain the same: understand your servo’s torque and speed requirements, provide clean power, and write clean control code.
Now go build your own smart bin—and never touch a trash can lid again.
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 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
- Using Raspberry Pi to Control Servo Motors in Smart Home Devices
- Creating a Servo-Controlled Automated Curtain System with Raspberry Pi
- Building a Servo-Powered Automated Sorting System with Raspberry Pi and Computer Vision
About Us
- Lucas Bennett
- Welcome to my blog!
Hot Blog
- Advances in Vibration Isolation for Micro Servo Motors
- Micro Servo vs Standard Servo: Impact of Size on Deadband
- Micro Servo Motor Gear Material Effects on Robot Longevity
- Integrating Multiple Servo Motors with Raspberry Pi
- How Gear Materials Affect Servo Motor Performance Under Varying Signal Delays
- Micro Servo Motor Price Comparison: Which Brands Offer the Best Deals?
- How to Implement Sensors in Control Circuits
- How Blockchain Technology Could Influence Micro Servo Motors
- Micro Servo Motor Behavior Under Shock & Impact in Robots
- BEGE's Micro Servo Motors: Tailored Solutions for Industrial Applications
Latest Blog
- Creating a Servo-Controlled Automated Trash Can Lid with Raspberry Pi
- Smart Kitchen Hood Doors with Micro Servo Mechanisms
- How Gear Materials Affect Servo Motor Performance Under Varying Signal Interferences
- Micro Servo Motor Control Signals: How They Drive Motion
- Specification of Slip-Ring or Shaft-Sealing in Waterproof Servos
- Using Micro Servos for Drone Parachute Deployment Systems
- Using Arduino to Control the Rotation Angle, Speed, and Direction of a Micro Servo Motor
- How to Maintain and Upgrade Your RC Car's Shock Absorber Seals
- How to Maintain and Upgrade Your RC Car's Spur Gear Mesh
- Micro Servos Designed for UV Exposure Resistance
- Micro Servo Motors in Automated Packaging Systems
- The Role of Micro Servo Motors in Industrial Automation
- Micro Servo Motors in Automated Sorting Systems
- Creating a Servo-Controlled Automated Pet Feeder with Arduino
- The Role of Micro Servo Motors in Collaborative Robotics
- Auto Locking Garage Door Latches with Micro Servos
- The Impact of 5G Technology on Micro Servo Motor Performance
- Understanding the Thermal Conductivity of Motor Materials
- Micro Servos for Articulated Robot Arms vs Fixed Mounts
- How to Build a Remote-Controlled Car with a Digital Proportional System