Cultivate Curiosity, Inspire Imagination.

Raspberry Pi Tutorial: Smart Dustbin Part 2


The Raspberry Pi Smart Dustbin is constructed by connecting an ultrasonic sensor and 3 LED lights to the Raspberry Pi to sense and indicate the level of fullness of a dustbin. In a real-life situation, a smart dustbin will allow users as well as cleaners to spot at one glace, which dustbins in the vicinity are still usable, and which ones need to be emptied.

In the second part of this tutorial, we explain how the Smart Dustbin can be monitored via the Internet by integrating the features of Thingspeak (, an IoT analytics platform that lets devices send data streams and allows users to visualize them on the cloud.




Hardware Required

You may also choose to purchase the individual components here:

  1. Raspberry Pi 4 4GB / 8GB
  2. Raspberry Pi 4 Power Supply 15.3W USB-C
  3. Micro SD Card 32GB Class 10
  4. Ultrasonic Sensor HC-SR04+ 3.3V Compatible
  5. LED Kit 5mm 3mm 100pcs
  6. Resistor Kit 1/4W 1-3M ohm 2600pcs
  7. Solderless Breadboard 830 Tie Point
  8. Raspberry Pi 4.3 inch DSI Interface Capacitive Touch Display with Case 800x480 (optional)
  9. Wireless Keyboard with Touchpad (optional)


Connecting the Hardware

Follow the instructions in the first part of the Smart Dustbin tutorial to learn how to connect the hardware.


Setting up ThingSpeak Cloud Dashboard

ThingSpeak is an open-source Internet of Things (IoT) application and API to store and retrieve data from things using the HTTP and MQTT protocol over the Internet or via a Local Area Network. ThingSpeak enables the creation of sensor logging applications, location tracking applications, and a social network of things with status updates.

Register for a free account on ThingSpeak (

Under the “Channels” tab, click “New Channel”

Fill in the Name and Description of the project. Under the fields section, tick checkbox for “Field 1” and label it “Capacity”. This is what we will be measuring from our Raspberry Pi. Once done, click “Save Channel” at the bottom. You should see a new Channel created for Smart Dustbin.

Create a new widget to visualise our dustbin capacity. Click “Add Widgets”.

We will be adding Gauge to display our dustbin capacity. Select “Gauge” and click “Next”.

Fill in the details of the widget. Once done, click “Create”.

You should see a new gauge appearing beside field 1 chart. The values are not available now because we have not sent any data yet. And with that, we are done with the dashboard!

Next, click on the “API Keys” tab. Take note of the Channel ID and the Write API Key. We will be using those in our program later.


Connecting the Smart Dustbin Program to ThingSpeak

Start up the Raspberry Pi. Launch the terminal and type in the following command to install ThingSpeak library.

sudo pip3 install thingspeak

Next, open "Thonny Python IDE". Edit the Smart Dustbin Python program in part 1. We will be making modifications to the program to allow it to send the Smart Dustbin's capacity to ThingSpeak.

Import the ThingSpeak library

# include libraries
import RPi.GPIO as GPIO
import time
import thingspeak


After initialising the pins, we will add a new variable lastSyncTime to keep track of the last time we sent any data to ThingSpeak. This is necessary if you are using the free version of ThingSpeak because the free version of ThingSpeak allows us to sync data to the platform only once every 15 seconds.

# declare variable
lastSyncTime = 0

You would have copied the Channel ID and Write API Key in the previous step when you set up ThingSpeak. Paste the Channel ID and Write API Key in the channel_id and write_key variables. This will allow the Python program to connect to ThingSpeak.

# setup thingspeak parameters
channel_id = xxxxxx # input your Channel ID
write_key = 'xxxxxx' # input your write key
channel = thingspeak.Channel(id=channel_id, api_key=write_key)


As we will be displaying the Smart Dustbin's capacity in the Capacity Gauge that we have added to our ThingSpeak channel, create a function to convert the distance values to percentage.

# function to re-map a number from one range to another
def translate(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min


Rename the function to get_capacity as we will be returning a 0-100% value instead. Using the distance we get from the ultrasonic sensor, we will map the values to 0-100% and constrain the values between 0 and 100.

def get_capacity():
# create a 10 microsecond pulse to trigger the ultrasonic module

# set ultrasonic trigger pin to high
GPIO.output(trigPin, True)
# wait for 10 microsecond
# set ultrasonic trigger pin to low
GPIO.output(trigPin, False)

# after pulsing, we need to listen for a signal

# record start time of no signal
while GPIO.input(echoPin) == 0:
pulse_start = time.time()

# record end time of a received signal
while GPIO.input(echoPin) == 1:
pulse_end = time.time()

# find the time difference between the signals
pulse_duration = pulse_end - pulse_start

# multiply with the speed of sound (34300 cm/s)
# and divide by 2 to get distance, because there and back
distance = (pulse_duration * 34300) / 2

# map distance range into percentage range
percentage = translate(distance, 35, 15, 0, 100)

# return the constrained values of min and max to 0 and 100
return max(min(100, percentage), 0)


Create another function so we can get the running time in milliseconds. This will be used to compare against the previous time we sent the data.

def millis():
return time.time() * 1000


We are subtracting lastSyncTime from the millis() function to find out if 15 seconds have passed between the last time we sent the Smart Dustbin's capacity to ThingSpeak. If it has already been 15 seconds, we proceed to re-send an updated Smart Dustbin capacity to ThingSpeak via channel.update({'field1': capacity}).

while True:
# get distance from the ultrasonic sensor
capacity = get_capacity()
print("Dustbin Capacity: %i%%" % capacity)

if capacity > 75:
elif capacity > 50:

# send data to ThingSpeak every 15s
# free account has an api limit of 15s
if (millis() - lastSyncTime > 15000):
# send data to ThingSpeak
channel.update({'field1': capacity})
print("Update success! Data: %i" % capacity)
print("Connection to ThingSpeak failed!")
lastSyncTime = millis()

# add some delay so the previous signal does not interfere with new signal


Run the updated Smart Dustbin program. Login to the ThingSpeak dashboard. Notice that the Capacity gauge changes as the Smart Dustbin gets filled up. This new feature allows us to keep track of the capacity of our dustbin in real-time. Most interestingly, we can view this dashboard anywhere in the world as long we can log in to our ThingSpeak dashboard!