© Guillermo Guillen 2019
G. GuillenSensor Projects with Raspberry Pihttps://doi.org/10.1007/978-1-4842-5299-4_4

4. Weather Station

Guillermo Guillen1 
(1)
Ciudad de Mexico, Mexico
 

The main goal of this project is to develop a weather station with Raspberry Pi and to be able to monitor all the sensors with ThingSpeak and Twitter. The sensors used without any problems are the DHT11 (humidity and temperature sensor) and the BMP085 (barometric pressure and temperature sensor).

Why not use the DHT22, BMP180, or the BMP280? The reasons are because the manufacturers are always going to come out with new versions of these sensors and I’d never finish this chapter and book. Don’t worry; the adjustments will be minimal between one sensor version and another.

A weather station is a facility, either on land or sea, with instruments and equipment for measuring atmospheric conditions to provide information for weather forecasts and to study the climate. The measurements taken include temperature, atmospheric pressure, humidity, wind speed, wind direction, and precipitation amounts. Wind measurements are taken with as few other obstructions as possible, while temperature and humidity measurements are kept free from direct solar radiation or insulation. Manual observations are taken at least once a day, while automated measurements are taken at least once an hour. In this chapter, you will limit yourself to measuring humidity, temperature, barometric pressure, and height above sea level.

Hardware

Make the electrical connections of the diagram in Figure 4-1.
../images/486908_1_En_4_Chapter/486908_1_En_4_Fig1_HTML.jpg
Figure 4-1

Electrical diagram

The barometric pressure sensor BMP085 is used to measure the atmospheric pressure between 300 and 1100hPa. It can also measure between -500 and 9000 meters above sea level, making the corresponding calculations. Additionally, it measures the temperature from 0 to 65 degrees centigrade. You must activate the 12C interface on the Raspberry Pi Configuration screen and reboot the system for it to work correctly. You can download the library from the link provided at the end of this tutorial.

The DHT11 sensor measures the relative humidity between 20% and 90%; it also measures the temperature between 0 and 50 degrees Celsius. The digital output is through a simple signal bus.

When the communication between the application and the Raspberry Pi board is established, you can perform the following functions in an interactive way:
  1. 1.

    The sensors begin to work and perform the tasks that correspond to them.

     
  2. 2.

    The DHT11 sensor measures the relative humidity and temperature in degrees Celsius and sends the data to the Raspberry Pi board.

     
  3. 3.

    The BMP085 sensor sends the barometric pressure data in hPa and the temperature in degrees Celsius to the Raspberry Pi board. Here you make the conversion to mmHg.

     
  4. 4.

    You print the measured values on the screen.

     
  5. 5.

    You send the following measured values to the ThingSpeak server: temperature measured by the DHT11 sensor, humidity measured by the DHT11 sensor, pressure measured in mmHg by the BMP085 sensor, and height calculated by the BMP085 sensor.

     
  6. 6.

    The ThingSpeak server sends a ThingTweet when the temperature is above 25 degrees Celsius and another ThingTweet when the humidity is above 45%.

     
The following are the parts needed for this project:
  • Raspberry Pi Zero W

  • DHT11 humidity sensor

  • BMP085 barometric pressure sensor

  • Resisitor 4k7

Figures 4-2 through 4-5 show this project.
../images/486908_1_En_4_Chapter/486908_1_En_4_Fig2_HTML.jpg
Figure 4-2

Testing the weather station

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig3_HTML.jpg
Figure 4-3

Top view with sensors DHT11 and BMP085

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig4_HTML.jpg
Figure 4-4

BMP085 barometric pressure sensor

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig5_HTML.jpg
Figure 4-5

DHT11 humidity sensor

Software

The complete source code and libraries can be found at https://drive.google.com/file/d/1QPtOBx8qhAONMWu0krrJI--6M86ZPoZE/view?usp=sharing.

Here, I’ve added comments here to better explain what the code is doing. They are marked by # and do not need to be reproduced when entering the code.
//********************************
# Script will be used to read sensor data and then post the IoT Thinkspeak
# Read Temperature & Humidity using DHT11 sensor attached to Raspberry PI Zero W
# Read Pressure and Altitude using BMP085 sensor attached to Raspberry PI Zero W
# Program posts these values to a thingspeak channel
# 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
import Adafruit_BMP.BMP085 as BMP085
DEBUG = 1
# Define GPIO pin to which DHT11 is connected
DHTpin = 4
#Setup our API and delay
myAPI = " GET_YOUR_KEY"  # API Key from thingSpeak.com channel
myDelay = 15 #how many seconds between posting data
GPIO.setmode(GPIO.BCM)
def getSensorData():
    print "In getSensorData";
    humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)
    sensor = BMP085.BMP085()
    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
        TWF=((9.0/5*temperature)+32)
        print('TempF={0:0.1f}*F'.format(TWF))
#        print('Temp = {0:0.2f} *C'.format(sensor.read_temperature()))
        Pressure = sensor.read_pressure()
        Altitude = sensor.read_altitude()
        print('Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()))
        print('Altitude = {0:0.2f} m'.format(sensor.read_altitude()))
    else:
        print('Failed to get reading. Try again!')
    return (str(humidity), str(temperature), str(Pressure), str(Altitude))
def main():
    print 'starting...'
    baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
    print baseURL
    while True:
        try:
            print "Reading Sensor Data now"
            RHW, TW, Pressure, Altitude = getSensorData()
            print TW + " " + RHW + " " + Pressure + " " + Altitude + " "
            f = urllib2.urlopen(baseURL + "&field1=%s&field2=%s&field3=%s&field4=%s" % (TW, RHW, Pressure, Altitude))
            print f.read()
            f.close()
            sleep(int(myDelay))
        except Exception as e:
            print e
            print 'exiting.'
            break
# call main
if __name__ == '__main__':
    main()
//******************************
Here is an example of what to do if you use another sensor. If you use the BMP180 sensor, download the library for this sensor, and change the following line:
import Adafruit_BMP.BMP180 as BMP180
Also, change the next line of code:
sensor = BMP180.BMP180 ()

Many of your doubts will be eased when you test the sensors. For example, I suggest you try the DHT humidity sensor with this example from the library:

AdafruitDHT.py
//******************************
import sys
import Adafruit_DHT
# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
                '22': Adafruit_DHT.DHT22,
                '2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
    sensor = sensor_args[sys.argv[1]]
    pin = sys.argv[2]
else:
    print('usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#')
    print('example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4')
    sys.exit(1)
# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32
# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
    print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
else:
    print('Failed to get reading. Try again!')
    sys.exit(1)
//******************************

For sensor BMP085, you can test it with the following code:

Simpletest.py
//******************************
import Adafruit_BMP.BMP085 as BMP085
# Default constructor will pick a default I2C bus.
#
# For the Raspberry Pi this means you should hook up to the only exposed I2C bus
# from the main GPIO header and the library will figure out the bus number based
# on the Pi's revision.
# For the Beaglebone Black the library will assume bus 1 by default, which is
# exposed with SCL = P9_19 and SDA = P9_20.
sensor = BMP085.BMP085()
# Optionally you can override the bus number:
#sensor = BMP085.BMP085(busnum=2)
# You can also optionally change the BMP085 mode to one of BMP085_ULTRALOWPOWER,
# BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES.  See the BMP085
# datasheet for more details on the meanings of each mode (accuracy and power
# consumption are primarily the differences).  The default mode is STANDARD.
#sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
print('Temp = {0:0.2f} *C'.format(sensor.read_temperature()))
print('Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()))
print('Altitude = {0:0.2f} m'.format(sensor.read_altitude()))
print('Sealevel Pressure = {0:0.2f} Pa'.format(sensor.read_sealevel_pressure()))
//******************************

Now that you have assembled the hardware pieces and you’ve programmed your Raspberry Pi board, you may have some problems with the installation of the libraries or with the configuration of the IoT server. This is what the next section is about.

Procedure

In the following sections, you will correctly install the libraries and also learn to configure the IoT server. Remember that in the previous chapters you used analog and digital sensors, but now you are using sensors with the 12C protocol interface from different manufacturers.

Installing the DHT11 Sensor Library

The DHT11 moisture sensor library is attached at the end of this tutorial and is called Adafruit_Python_DHT-master.zip.

Optionally, you can download the library from https://github.com/adafruit/Adafruit_Python_DHT.git.

Unzip the package. To execute the installation, type the following in the command line:
>>> sudo python setup.py install

In the library you can find simple examples to test this sensor.

Installing the BMP085 Sensor Library

The BMP085 pressure sensor library is attached at the end of this tutorial and is called Adafruit_Python_BMP-master.zip.

Optionally, you can download the library from
https://github.com/adafruit/Adafruit_Python_BMP.
Unzip the package. To execute the installation, type the following in the command line:
>>> sudo python setup.py install

In the library you can find simple examples to test this sensor.

Enabling the 12C Interface

You must activate the 12C interface on the Raspberry Pi Configuration screen and reboot the system for it to work correctly.

Creating a Project in ThingSpeak

Use the account you created earlier and create a new channel. Enter the following data (Figure 4-6):
  • Name: WeatherStation

  • Description:

  • Field1: Temperature (C)

  • Field2: Humidity (%)

  • Field3: Pressure (hPa)

  • Field4: Altitude (m)

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig6_HTML.jpg
Figure 4-6

Creating a new channel

Save the project. The system will provide you with the channel number and the Write API key.

Copy the Write API key, which is 16 characters, and paste it into the Python code where it says
myAPI = "GET_YOUR_KEY"

Remember that in the free account in ThingSpeak you can only monitor a maximum of four channels simultaneously.

With this configuration, you can get the information shown in Figures 4-7 through 4-11.
../images/486908_1_En_4_Chapter/486908_1_En_4_Fig7_HTML.jpg
Figure 4-7

Four graphs on the ThingSpeak server

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig8_HTML.jpg
Figure 4-8

Temperature graph

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig9_HTML.jpg
Figure 4-9

Humidity graph

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig10_HTML.jpg
Figure 4-10

Pressure graph

../images/486908_1_En_4_Chapter/486908_1_En_4_Fig11_HTML.jpg
Figure 4-11

Altitude graph

Using Your Twitter Account in ThingSpeak

If you registered your Twitter account in Chapters 2 and 3, then it’s not necessary to repeat this step. If this is not the case, you should click Apps ➤ ThingTweet. You must link your Twitter account. The system will provide you with an API Key.

Sending an Alert to Your Twitter Account

Click Apps and React. Then fill out the new React as follows (Figure 4-12):
  • React Name: WeatherStation – temperature

  • Condition type: Numeric

  • Test Frequency: On data insertion

  • Condition: If channel WeatherStation temperature is greater than 25

  • Action: ThingTweet

  • Then tweet: “From WeatherStation – temperature is above 25 degrees Celsius”

  • Using Twitter account: “YOUR TWITTER LOGIN”

Options: Run action only the first time the condition is met.
../images/486908_1_En_4_Chapter/486908_1_En_4_Fig12_HTML.jpg
Figure 4-12

Create a new React and fill in this data for the temperature

Do the same with the humidity React data:
  • React Name: WeatherStation – humidity

  • Condition type: Numeric

  • Test Frequency: On data insertion

  • Condition: If channel WeatherStation humidity is greater than 45

  • Action: ThingTweet

  • Then tweet: “From WeatherStation – humidity is above 45 %”

  • Using Twitter account: “YOUR TWITTER LOGIN”

  • Options: Run action only the first time the condition is met.

Now you can get the next tweet alert (Figure 4-13).
../images/486908_1_En_4_Chapter/486908_1_En_4_Fig13_HTML.jpg
Figure 4-13

Alert sent to my Twitter account

Challenges

Use the next sensors: DHT22, BMP180, and BMP280.

Conclusion

In this chapter, you used the 12C and One Wire protocols to build a weather station with your Raspberry Pi. Additionally, you tested the ThingSpeak server to display four graphs of your IoT system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.32.116