Raspberry Pi Tutorial: Smart Dustbin Part 2

Introduction

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 (https://thingspeak.com/), an IoT analytics platform that lets devices send data streams and allows users to visualize them on the cloud.

 

Hardware Required

In this example we are using Raspberry Pi Starter Kit, which includes various sensors and modules to get started right out of the box.

You may also choose to purchase the individual components here:

  1. Raspberry Pi 4 4GB or Raspberry Pi 8GB
  2. Raspberry Pi 4 Power Supply 15.3W USB-C
  3. Micro SD Card 16GB or Micro SD Card 32GB
  4. Ultrasonic Sensor HC-SR04+ 3.3V Compatible
  5. LED Kit 5mm/3mm 125 pcs
  6. Resistor Kit 1/4W 1280 pcs
  7. Solderless Breadboard 830 Tie Point
  8. Raspberry Pi 5.5" HDMI Capacitive Touch AMOLED + Case 1080×1920 (optional)
  9. Wireless Keyboard with Touchpad for Raspberry Pi and LattePanda (optional)

 

Raspberry Pi 4 4GB/8GB

A Raspberry Pi is a compact computer board offering endless opportunities. From the beginning, the Raspberry Pi was designed to be simple to use and simple to adapt to what you want to do with it.

Simply plug into a TV or monitor, keyboard, mouse, and power supply, and you are ready to go. The great thing about Raspberry Pi is that it is suitable for almost all age groups. Whether it’s introducing programming to children, or used by engineers to make complex computer-controlled systems, anyone can use one.

Raspberry Pi 4 Power Supply 15.3W USB-C

The Raspberry Pi 4 USB-C Power Supply provides the necessary 5.1V/3.0A DC power to power the Raspberry Pi 4.

Micro SD Card 16GB/32GB

The Micro SD Card stores the Raspberry Pi's operating systems as well as files that you will be creating and reading from in your projects. Read more about how you can install the Raspberry Pi OS here. Or better still purchase an SD Card with the Raspberry Pi OS installed at our online store!

Ultrasonic Sensor HC-SR04+ 3.3V Compatible

The Ultrasonic Sensor HC-SR04+ uses sonar to determine the distance to objects like bats or dolphins do. This module offers excellent range accuracy and stable readings in an easy-to-use package. Its operation is not affected by sunlight or black material (although acoustically soft materials like cloth can be difficult to detect). Ranging accuracy can reach up to 3mm.

LED Kit 5mm/3mm 125 pcs

An assortment of red, yellow, green, white and blue LEDs packed into a kit. Save the hassle of trying to purchase individual LEDs. Having extra LEDs around is always handy, almost all project requires some sort of LED whether its for indication light, alarm light, feedback light and many more.

Resistor Kit 1/4W 1280 pcs

An assortment of 1/4W resistors packed into a kit. Save the hassle of trying to purchase individual resistors. Having extra resistors around is always handy for any prototyping, especially if you're trying to figure out what resistor values to use for voltage dividers.

Solderless Breadboard 830 Tie Point

Solderless breadboard is perfect for prototyping. No hassle of soldering wires. All connections can be connected via jumper wires. There is a strip of double-sided tape at the bottom of the breadboard so you can fix the breadboard in place.

Raspberry Pi 5.5" HDMI Capacitive Touch AMOLED + Case 1080×1920

The Raspberry Pi 5.5" HDMI Capacitive Touch AMOLED + Case is an all-in-one LED display with a capacitive touchscreen as well as an enclosure to keep your Raspberry Pi all together in an attractive-looking package.

Wireless Keyboard with Touchpad for Raspberry Pi and LattePanda

This is a wonderful combo, 2.4GHz Mini Wireless QWERTY keyboard mouse, TouchPad combo, with USB interface adapter for Raspberry Pi, Cubieboard, Mini PC, and others. The Ergonomically handheld design is easy to carry and operate. Build-in removable rechargeable Li-ion battery that has a longer standby time. Perfect for PC, Pad, Andriod TV Box, Google TV Box, Xbox360, PS3, HTPC/IPTV, and Raspberry Pi, etc.

 

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 (https://thingspeak.com/).

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
time.sleep(0.00001)
# 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:
  show_LED("red")
elif capacity > 50:
  show_LED("blue")
else:
  show_LED("green")

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

# add some delay so the previous signal does not interfere with new signal
time.sleep(0.1)

 

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!

Resources