Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
Smart Can
This is an Arduino code designed to control a smart garbage can. When an object is within a 20-centimeter range in front of the garbage can, its lid automatically opens. This project utilizes an SG90 servo motor and an HC-SR04 ultrasonic distance sensor.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
---|---|---|
Elite Explorer Kit |
300+ |
You can also buy them separately from the links below.
COMPONENT INTRODUCTION |
PURCHASE LINK |
---|---|
- |
|
Wiring

Schematic

Code
Note
You can open the file
07_smart_trash_can.ino
under the path ofelite-explorer-kit-main\fun_project\07_smart_trash_can
directly.Or copy this code into Arduino IDE.
How it works?
Here is a step-by-step explanation of the code:
Import Libraries and Define Constants/Variables:
The
Servo.h
library is imported for controlling the SG90 servo motor. Parameters for the servo motor, ultrasonic sensor, and other required constants and variables are defined.setup()
:Initialize serial communication with the computer at a baud rate of 9600. Configure the trigger and echo pins of the ultrasonic sensor. Attach the servo motor to its control pin and set its initial position to the closed angle. After setting the angle, the servo motor is detached to save power.
loop()
:Measure distance three times and store the values of each measurement. Calculate the average distance from the three measurements. If the average distance is less than or equal to 20 centimeters (defined distance threshold), the servo motor rotates to the open angle (0 degrees). Otherwise, the servo motor returns to the closed position (90 degrees) after a one-second delay. The servo motor is detached when not in use to conserve power.
readDistance()
:Send a pulse to the trigger pin of the ultrasonic sensor. Measure the pulse width of the echo pin and calculate the distance value. This calculation uses the speed of sound in the air to compute distance based on pulse time.