Build Your First IOT With a Raspberry Pi, DHT11 Sensor, and Thingspeak.

158,850

352

45

Introduction: Build Your First IOT With a Raspberry Pi, DHT11 Sensor, and Thingspeak.

About: Soldering Sunday was started by a couple of Makers. We are dedicated to providing a supportive environment for Makers of all skill sets from the absolute beginner to the seasoned Maker. Our goal is to help y...

IOT or Internet of Things is a hot topic! According to the experts everything will be connected to the internet and all our devices and their data will soon be just an IP address away from us. So where do you start if you want to explore the world of IOT? How about a simple Temperature, Humidity, and Light sensor for your basement.

Summer is here and being in the Northeast that means HUMIDITY with a capital HUMID. Many of us have some sort of de-humidification system in our basements. My workshop is in my basement and I have a small dehumidifier that keeps it nice a dry during these months. Despite the basement being humid it is also cooler than the above ground summer temps. I decided that I wanted to know how cool and how humid it can be and thus it became the inspiration for my first IOT project.

DHT11 sensors measure temperature and relative humidity and are cheap. Perfect for a first project. The DHT11 is not what I would call "scientifically" accurate but it is good enough to monitor my basement. While I was at it, I figured I might as well add a light sensor to know if I left the lights on. Another simple and cheap solution, all I need to use is a photoresistor.

Where to put the data became the next question. I could build a web server, but I wanted this to be simple so I decided to leverage a service called Thingspeak that has an API and will let me post and review the data from my IOT monitor.

Step 1: What You Need to Complete This Project

Lets get started on building our project. We will build this on a breadboard, so no need to worry about soldering, or a designing pcb. Once we are happy with the design we can do that.

Hardware:

-Raspberry PI 2 & SD Card with Raspbian Operating System
-USB Power Supply
-USB Cable
-Breadboard & Jumper Wires
-2 x DHT 11 sensors
-2 x 10K Resistors
-2 x Photocells
-2 x 1uF Capacitors

Step 2: Prep the Raspberry PI

If you have not done so, load Raspbian on your Raspberry PI. If you don't have a Raspberry PI, you can get one at Soldering Sunday that includes NOOBS pre-loaded on the MicroSD card or you can follow our guide to loading the Operating System for your Raspberry PI.

Once your Raspberry Pi is up and running we need to setup Python to talk to the GPIO pins. The GPIO pins are our interface to the DHT11 Temp/Humidity sensor and the photocell. For a deeper look at the Raspberry Pi GPIO Pin's go to our GPIO Tutorial.

Configuring Python

Not all the libraries we need to make this project are pre-loaded on the Raspberry Pi. You will need the Adafruit GPIO Python library and the Adafruit DHT 11 library.

We will use Adafruit's guide and library for setting up Python to communicate with the Raspberry Pi GPIO pins.
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-gpio

We also need Adafruit's Python library for the DHT11 sensor, which you can find here:
https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/overview

Step 3: Raspberry PI - Understanding GPIO Pins

GPIO stands for General Purpose Input/Output and on the Raspberry Pi they are the physical interface between the software side of the Raspberry PI and the outside world. We will need to use the GPIO pins to connect to the DHT11 and the Photoresistor.

Different versions of the Raspberry Pi have a different amount of GPIO pins. In early versions of the Raspberry Pi there were 26 pins and the more recent versions have 40 pins. Even though more pins were added, pins 1 through 26 are the same on all versions. When you look at a reference for Raspberry Pi GPIO pins you will will find several notations for each pin. Most commonly you will find one reference for the physical name of the pin (1 to 40) and the other for the GPIO Name (GPIO1, etc). The physical name is just that, the physical ordered number of the pin. With Python we will be using the GPIO reference for our pin identification. The GPIO Name is designated from the chip set and more commonly used in advanced projects.

Referencing the wrong GPIO Pin number is very common and if you are not getting the results you expect when working with GPIO, double check the pin you are connected to and the pin you are referencing in your code.

If you would like a more in-depth review of the Raspberry Pi GPIO pins, we have a tutorial on them on our site.

Step 4: Build the Circuit

We are keeping the circuit simple and building it on a breadboard using our components and jumper wires. Before connecting anything to your Raspberry PI, disconnect the power.

Warning - you can destroy your Raspberry Pi with a short circuit from a wrong connection. Just be careful and double check everything before powering back on.

To connect from the Raspberry PI to breadboard I like to use Dupont Cables, they are jumper wires that have a female side and a male side. The female side connects right to the male header pins of he Raspberry Pi and the male side plugs right into the Breadboard.

For this circuit we need to use the 3.3v out from the Raspberry Pi Pin 1 (do not use the 5v on Pin 2) and we need Ground (GND) of course. Connect these from the Pi to the Breadboard.

The DHT 11 has 4 Pins. Pin 1 is VCC, Pins 2 is Data, Pin 3 is NOT USED, Pin 4 is Ground.

  • Connect DHT 11 Pin 1 to 3.3v
  • Connect DHT 11 Pin 2 to Raspberry PI Pin 16/GPIO 23 and connect a 4.7 or 10k resistor from DHT 11 Pin 2 to DHT Pin 1
  • Connect DHT 11 Pin 4 to Ground

The photo resistor has 2 pins

  • Connect one pin to 3.3.v
  • Connect the Other Pin to Raspberry Pi Pin 18/GPIO 24
  • Connect a 1uF Capacitor to the same pin that the photo resistor is connected to on GPIO24. The Ground (White Stripe) side of the capacitor should go to Ground.

Check your work against the attached Fritzing Diagram and the photos.

Step 5: Setup Thingspeak for Our IOT Data

Our Python script is going to read data from the DHT11 sensor and the photoresistor and then publish the values of that data to our channel on Thingspeak. First we need to set it up.

Go to Thingspeak.com and create a free acount or login to you existing account. Click on "My Channels" and then click on New Channel. Name your new channel and name the fields. The order of the fields is important later when we post data. They can be in any order, but when you post the data the data you need to remember position.

You can decide if you want the channel to be public or not as well as publish information about it's location. This is all up to you and will not affect our code. You will also need the Write API key for the channel as it will be required to post data to the channel.

Step 6: Mini-intro to Python

Python has been around for many years and is has made a roaring comeback as the goto language for developers of all skill levels. It is an easy and clean language for the beginner and a powerful option for the advanced developer. It was a perfect choice for the Raspberry Pi. On the Raspberry Pi you will notice that there is a Python 2 and a Python 3 option. We will be working in Pyhton 3.

Why Python 3?

Good question. To answer you I will quote from the Python Wiki: "Python 2.x is legacy, Python 3.x is the present and future of the language"

Where can I learn more about Python?

Start at the source, python.org or try your hand at Python onlie at Code Academy. For a tutorials on Python on the Raspberry PI go here.

Launch IDLE on the Raspberry Pi

Most programming languages have a Integrated Development Environment, or IDE, and Python is no different. For Python it is called IDLE which also stands for Integrated DeveLopment Environment. IDLE is essentially a souped up text editor that understands you are coding in Python and will highlight your syntax and provide shortcuts to help you write your code. It will also help validate that your syntax is correct.

To Launch IDLE on the Raspberry Pi go to MENU -> Programming -> Python 3

To start writing our script go to FILE -> NEW and a new, untitled window will appear. This is where we will actually write our code. Save and name the file before we begin. Go to FILE ->Save and the file myfirstIOT.py

Take note of the directory you saved it in. It is probably /home/pi

Don't forget to add the ".py" at the end of your file, IDLE will not add it automatically.

Step 7: Create the Python Script

Download the attached Python Script. You can copy paste to your IDLE session or download it to your Raspberry PI and save it in the /pi folder.

Before running it be sure to edit your API key from your ThingSpeak channel - edit this line:

#Setup our API and delay
myAPI = "***Insert Your API CODE HERE***"


Step 8: Start Your IOT Engine!

We are ready to turn on our IOT engine - all we need to do is run our script.

Open LXTerminal. At the default command prompt you should be in the /pi directory already. You can type LS to see the file listings and the myfirstIOT.py should be there. We need SUDO (administrative) rights for script to access the GPIO Pins, so run the script as follows:

sudo python myfirstIOT.py

You should see the base url printed with your API key and the next line will be data from the DHT 11.

Each line printed locally will display:

Temp (c) - Temp (f) - Humidity - Light ( 0=off / 1=on)

Then go check you Channel on Thingspeak, you should have data.

SUCCESS! You Did it!
You are now part of the Internet of Things revolution.

In the age of Google and mass collaboration, it must be said that nothing we are doing here is original or has not been done before. We are just putting together components of software and hardware to solve the challenge we have. With that said, it means that if I can do it, you can do it too. What will you do next? Take this and expand on it.

10 People Made This Project!

Recommendations

  • Metalworking Contest

    Metalworking Contest
  • Fix It! Contest

    Fix It! Contest
  • Water Contest

    Water Contest

45 Discussions

Here is the correct code!

"""

My First Internet of Things

Temperature/Humidity Light monitor using Raspberry Pi, DHT11, and photosensor

Data is displayed at thingspeak.com

2015/06/15

SolderingSunday.com

Based on project by Mahesh Venkitachalam at electronut.in

"""

# Import all the libraries we need to run

import sys

import RPi.GPIO as GPIO

import os

from time import sleep

import Adafruit_DHT

import urllib2

DEBUG = 1

# Setup the pins we are connect to

RCpin = 24

DHTpin = 23

#Setup our API and delay

myAPI = "***Insert Your API CODE HERE***"

myDelay = 15 #how many seconds between posting data

GPIO.setmode(GPIO.BCM)

GPIO.setup(RCpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def getSensorData():

RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)

#Convert from Celius to Farenheit

TWF = 9/5*TW+32

# return dict

return (str(RHW), str(TW),str(TWF))

def RCtime(RCpin):

LT = 0

if (GPIO.input(RCpin) == True):

LT += 1

return (str(LT))

# main() function

def main():

print 'starting...'

baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI

print baseURL

while True:

try:

RHW, TW, TWF = getSensorData()

LT = RCtime(RCpin)

f = urllib2.urlopen(baseURL +

"&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+

"&field4=%s" % (LT))

print f.read()

print TW + " " + TWF+ " " + RHW + " " + LT

f.close()

sleep(int(myDelay))

except:

print 'exiting.'

break

# call main

if __name__ == '__main__':

main()

2 replies

Hlw.......i ran this corrected code before six month, it worked.But now i
m trying to run this code and it doesn't run.Its says """""""starting
https://api.thingspeak.com/update?api_key=%sYHG5O...
gets stack.Nothing comes after it.I tally the code with original code
and removed maximum error.But this error is still left.Can you please
help me with complete code????Please :) :) :)

Statements in this code are perfect. But if you copy paste the code here, You will definitely have indentation problem. Thus, i recommend to compare this code with the MyfirstIOT.py's code and complete the code.

Hello
Actually i m new to raspberry pi pls is anybody can help to add Adafruit library to my pi

I have made this project but i have not shot any pictures. Python program provided in the instructable has a lot of unwanted stuff in it. All the green colored (between """" """") is comment in python and one should delete those first. The remaining code is incomplete then. One should compare the code with the one given by AlainB18 and complete the end. Statement's in AlainB18's code are correct but lack python's syntax.

0
None
King90

1 year ago

sudo python myfirstIOT.py
File "myfirstIOT.py", line 68
"""
^
SyntaxError: invalid syntax

1 reply

Here is how to get the project to work:

Step 1

Replace my write API key Y5HGYOS51NFJ2I5O with your write api key in 3 lines (85,161 and 217).

Step 2

Save the file using the name dht11_thingspeak.py Iin the /home/pi folder

Step 3

You run the python script by entering this command in the command prompt. Replace YOURWRITEAPIKEY in the command with your write API key:

sudo python dht11_thingspeak.py YOURWRITEAPIKEY 

Here is the corrected python code:

#My First Internet of Things

#Temperature/Humidity Light monitor using Raspberry Pi, DHT11, and photosensor

#Data is displayed at thingspeak.com

#2015/06/15

#SolderingSunday.com

#Based on project by Mahesh Venkitachalam at electronut.in

# Import all the libraries we need to run

import sys

import RPi.GPIO as GPIO

import os

from time import sleep

import Adafruit_DHT

import urllib2

DEBUG = 1

# Setup the pins we are connect to

RCpin = 24

DHTpin = 23

#Setup our API and delay

myAPI = "Y5HGYOS51NFJ2I5O"

myDelay = 15 #how many seconds between posting data

GPIO.setmode(GPIO.BCM)

GPIO.setup(RCpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def getSensorData():

RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)

#Convert from Celius to Farenheit

TWF = 9/5*TW+32

# return dict

return (str(RHW), str(TW),str(TWF))

def RCtime(RCpin):

LT = 0

if (GPIO.input(RCpin) == True):

LT += 1

return (str(LT))

# main() function

def main():

print 'starting...'

baseURL

#My First Internet of Things

#Temperature/Humidity Light monitor using Raspberry Pi, DHT11, and photosensor

#Data is displayed at thingspeak.com

#2015/06/15

#SolderingSunday.com

#Based on project by Mahesh Venkitachalam at electronut.in

# Import all the libraries we need to run

import sys

import RPi.GPIO as GPIO

import os

from time import sleep

import Adafruit_DHT

import urllib2

DEBUG = 1

# Setup the pins we are connect to

RCpin = 24

DHTpin = 23

#Setup our API and delay

myAPI = "Y5HGYOS51NFJ2I5O"

myDelay = 15 #how many seconds between posting data

GPIO.setmode(GPIO.BCM)

GPIO.setup(RCpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def getSensorData():

RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)

#Convert from Celius to Farenheit

TWF = 9/5*TW+32

# return dict

return (str(RHW), str(TW),str(TWF))

def RCtime(RCpin):

LT = 0

if (GPIO.input(RCpin) == True):

LT += 1

return (str(LT))

# main() function

def main():

print 'starting...'

baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI

print baseURL

while True:

try:

RHW, TW, TWF = getSensorData()

LT = RCtime(RCpin)

f = urllib2.urlopen(baseURL +

"&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+

"&field4=%s" % (LT))

print f.read()

print TW + " " + TWF+ " " + RHW + " " + LT

f.close()

sleep(int(myDelay))

except:

print 'exiting.'

break

# call main

#My First Internet of Things

#Temperature/Humidity Light monitor using Raspberry Pi, DHT11, and photosensor

#Data is displayed at thingspeak.com

#2015/06/15

#SolderingSunday.com

#Based on project by Mahesh Venkitachalam at electronut.in

# Import all the libraries we need to run

import sys

import RPi.GPIO as GPIO

import os

from time import sleep

import Adafruit_DHT

import urllib2

DEBUG = 1

# Setup the pins we are connect to

RCpin = 24

DHTpin = 23

#Setup our API and delay

myAPI = "Y5HGYOS51NFJ2I5O"

myDelay = 15 #how many seconds between posting data

GPIO.setmode(GPIO.BCM)

GPIO.setup(RCpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def getSensorData():

RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)

#Convert from Celius to Farenheit

TWF = 9/5*TW+32

# return dict

return (str(RHW), str(TW),str(TWF))

def RCtime(RCpin):

LT = 0

if (GPIO.input(RCpin) == True):

LT += 1

return (str(LT))

# main() function

def main():

print 'starting...'

baseURL

#My First Internet of Things

#Temperature/Humidity Light monitor using Raspberry Pi, DHT11, and photosensor

#Data is displayed at thingspeak.com

#2015/06/15

#SolderingSunday.com

#Based on project by Mahesh Venkitachalam at electronut.in

# Import all the libraries we need to run

import sys

import RPi.GPIO as GPIO

import os

from time import sleep

import Adafruit_DHT

import urllib2

DEBUG = 1

# Setup the pins we are connect to

RCpin = 24

DHTpin = 23

#Setup our API and delay

myAPI = "Y5HGYOS51NFJ2I5O"

myDelay = 15 #how many seconds between posting data

GPIO.setmode(GPIO.BCM)

GPIO.setup(RCpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

def getSensorData():

RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)

#Convert from Celius to Farenheit

TWF = 9/5*TW+32

# return dict

return (str(RHW), str(TW),str(TWF))

def RCtime(RCpin):

LT = 0

if (GPIO.input(RCpin) == True):

LT += 1

return (str(LT))

# main() function

def main():

print 'starting...'

baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI

print baseURL

while True:

try:

RHW, TW, TWF = getSensorData()

LT = RCtime(RCpin)

f = urllib2.urlopen(baseURL +

"&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+

"&field4=%s" % (LT))

print f.read()

print TW + " " + TWF+ " " + RHW + " " + LT

f.close()

sleep(int(myDelay))

except:

print 'exiting.'

break

# call main

if __name__ == '__main__':

main()

baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI

print baseURL

while True:

try:

RHW, TW, TWF = getSensorData()

LT = RCtime(RCpin)

f = urllib2.urlopen(baseURL +

"&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+

"&field4=%s" % (LT))

print f.read()

print TW + " " + TWF+ " " + RHW + " " + LT

f.close()

sleep(int(myDelay))

except:

print 'exiting.'

break

# call main

if __name__ == '__main__':

main()

if __name__ == '__main__':

main()

baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI

print baseURL

while True:

try:

RHW, TW, TWF = getSensorData()

LT = RCtime(RCpin)

f = urllib2.urlopen(baseURL +

"&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+

"&field4=%s" % (LT))

print f.read()

print TW + " " + TWF+ " " + RHW + " " + LT

f.close()

sleep(int(myDelay))

except:

print 'exiting.'

break

# call main

if __name__ == '__main__':

main()

Can someone make a correct version of this myfirstIOT.py file please

Can someone make a correct version of this myfirstIOT.py file please

Nice project - But could someone explain why the capacitor is used?

Could someone post the actual correct python code for both sensors (as intended by the author). Thank you very much.

3 copies of the same code, you commented out one.. you're a boof

Very good project. There are some confusion with your code (maybe someone damage it, good take a look). I did mine and worked fine. The tip of Thigspeak was great! Thanks a lot.

Bellow a video with my experiment, including a Twitter alarm.

4 replies

Does it works if someone has a DHT11 Sensor, that is not manufactured by Adafruit,
Since we don't have Adafruit products in India :(
Kindly Help

yes, should have no problem. I tried with 3 different sensors, 2 from China and one from Amazon. All worked fine.

Very nice indeed. I am glad my project was helpful. You did a great job.

Really nice. I am glad my project helped you.

Does it works if someone has a DHT11 Sensor, that is not manufactured by Adafruit,
Since we don't have Adafruit products in India :(
Kindly Help

0
None
TimoB3

2 years ago

Hi there,

i got quite a few problems after running the script. The mistakes with the "" i fixed myself, but still there is the problem with the url.

Can someone please post a well working version of the script.

The project does look so nice - i would luv to try!

Thanks

1 reply