9
All-in-One Weather Sensor Station

In this project, you’ll build a local weather station that detects the temperature, humidity, and barometric pressure with the Sense HAT. You’ll also create a graphical user interface to display temperature, humidity, and barometric pressure readings in real time.

image

PARTS REQUIRED

Raspberr y Pi (versions with 40 GPIOs)

Sense HAT

THE SENSE HAT AS A WEATHER STATION

The Sense HAT makes an excellent small and affordable weather station, as it comes with temperature, humidity, and barometric pressure sensors. Reading sensor values with the Sense HAT is very straightforward, so this is a good starting point to learn about sensor readings.

The Temperature Sensor

NOTE

The temperature readings might be a few degrees off when compared to the real value. The Sense HAT fits over the Pi and the heat from the Raspberry Pi processor can alter the results slightly.

As the name suggests, the temperature sensor measures temperature. By default, the Sense HAT reads the temperature in degrees Celsius, so if you prefer the temperature in degrees Fahrenheit, you’ll need to convert the reading. To do so, multiply the degrees in Celsius by 9, divide by 5, and add 32, as shown in the following formula.

image

You can add this formula to your code so that it does the conversion for you.

The Humidity Sensor

There are two common ways of expressing humidity: absolute humidity and relative humidity. Absolute humidity is the mass of water vapor in a certain volume of air, regardless of temperature, and it is expressed as kilograms per cubic meter (kg/m3). The amount of water vapor that the air can hold changes with temperature. The higher the temperature, the more water vapor it can hold. Relative humidity is expressed as a percentage and is the current water vapor in the air in relation to the maximum possible amount at a given temperature.

The Sense HAT records relative humidity because it’s more useful for weather forecasts: the greater the relative humidity percentage, the higher the probability of precipitation. As relative humidity changes with temperature, it’s always coupled with a temperature sensor.

The Barometric Pressure Sensor

The barometric pressure sensor reads atmospheric pressure, the “weight” of the air at a given point, measured in hPa (hectoPascal), which is equivalent to mbar (millibar). Why is it interesting to measure pressure? Because changes in atmospheric pressure can help you forecast the weather. Rising pressure tends to be a sign of good weather to come, and falling pressure a sign of bad weather, like rain or storms.

Changes in pressure are really small. You need to follow your barometer readings meticulously to notice a trend.

READING TEMPERATURE, HUMIDITY, AND PRESSURE

Now let’s look at how to read from the sensors and print the readings to the Python shell.

Mount your Sense HAT on your Pi like you did in Project 8 and make sure it’s well connected. When it’s first connected, the Sense HAT should display a rainbow background that matches the rainbow you see on the screen when you boot your Pi (see Figure 9-1).

image

FIGURE 9-1: Sense HAT rainbow background

Inside your Projects folder create a new folder called Sensors. Then open Python 3 (IDLE) and go to File New to create a new script called weather_data.py and enter the code in Listing 9-1 (remember that you can download all the scripts at https://www.nostarch.com/RaspberryPiProject/ ).

LISTING 9-1: Reading temperature, humidity, and pressure with the Sense HAT

from sense_hat import SenseHat
  #from sense_emu import SenseHat

  from time import sleep

  #create an object called sense
sense = SenseHat()

  while True:
    temperature = sense.temperature
    temperature = str(round(temperature, 2))
    print('Temperature: ' + temperature + '*C ')
     humidity = sense.humidity
     humidity = str(round(humidity, 2))
     print ('Humidity: ' + humidity + '% ')

     pressure = sense.pressure
     pressure = str(round(pressure, 2))
     print('Pressure: ' + pressure + 'hPa ')

     sleep(1)

First you import the SenseHat class from the sense_hat library . Then, you create an object called sense to refer to the Sense HAT .

Getting the sensor readings is simple thanks to the following, aptly named functions:

  • sense.temperature gets the temperature reading.
  • sense.humidity gets the humidity reading.
  • sense.pressure gets the pressure reading.

The readings are given to several decimal places, so you use the function round() to round the numbers and make the results more readable. The round() function accepts as arguments the number you want to round and the number of decimal places you want to set, in that order—here, it’s set to two decimal places. You also use the str() function that converts the argument it takes into a string. You need to convert the readings into a string so you can concatenate them with the text you’ll print to the shell .

Now you’re almost a meteorologist! Next, you’ll build a user interface for your weather data.

BUILDING A USER INTERFACE FOR YOUR READINGS

Let’s take this project to another level and build a cool user interface to display your sensor readings. Your interface should feature:

  • A window in your desktop that displays temperature, humidity, and pressure
  • The humidity displayed in a vertical progress bar from 0 to 100 percent
  • The temperature and pressure displayed in numbers
  • Labels for each reading

Figure 9-2 shows a draft layout for the user interface that should help you work out how to go about the code.

image

FIGURE 9-2: Graphical user interface draft

You’ll also be able to edit the code to choose font type, size, and color, and how labels and readings are positioned within the window. The following table gives you a list of all the titles and values and how we’ll display them.

WIDGET

OPTIONS

Window Title

Text: “Local Weather Station”

Humidity Title

Text: “Humidity”, Font: Helvetica, Size: 18, Vertical padding: 3

Humidity Value

Font: Courier, Size: 20, Color: Blue, Position: North

Humidity Progress Bar

Orientation: Vertical, Size: 20, Color: Blue, Position: North, Length: 200, Maximum Value: 100

Temperature Title

Text: “Temperature”, Font: Helvetica, Size: 18, Position: South

Temperature Value

Font: Courier, Size: 20, Color: Red, Position: North

Pressure Title

Text: “Pressure”, Font: Helvetica, Size: 18, Position: South

Pressure Value

Font: Courier, Size: 20, Color: Green, Position: North

WRITING THE SCRIPT

Open Python 3 (IDLE) and go to File New File to create a new script. Copy the code in Listing 9-2 to the Python Editor and save the script as weather_station.py inside the Sensors folder (remember that you can download all the scripts at https://www.nostarch.com/RaspberryPiProject/):

LISTING 9-2: Displaying the Sense HAT readings in a graphical user interface

  #import necessary libraries
from tkinter import *
  from tkinter import ttk
  import time
  from sense_hat import SenseHat
  #from sense_emu import SenseHat

  #create an object called sense
  sense = SenseHat()

  #create window
window = Tk()
  window.title('Local Weather Station')
  window.geometry('200x480')

  #create humidity label for title and value
humidity_label = Label(window, text = 'Humidity', font =
  ('Helvetica', 18), pady = 3)
  humidity_label.pack()

humidity = StringVar()

humidity_value=Label(window, textvariable = humidity,font =
  ('Courier', 20), fg = 'blue', anchor = N, width = 200)
  humidity_value.pack()

  #create humidity canvas
humidity_canvas = Canvas(window, width = 200, height = 200)
  humidity_canvas.pack()

  #create humidity progress bar
humidity_bar = DoubleVar()

progressbar_humidity = ttk.Progressbar(humidity_canvas, variable =
  humidity_bar, orient = VERTICAL, length = 200, maximum = 100)
  progressbar_humidity.pack(fill=X, expand=1)

  #create temperature label for title and value
  temperature_label = Label(window, text = 'Temperature', font =
  ('Helvetica', 18),anchor = S, width = 200, height = 2)
  temperature_label.pack()

  temperature = StringVar()

  temperature_value = Label(window, textvariable = temperature, font =
  ('Courier', 20),fg = 'red', anchor = N, width = 200)
  temperature_value.pack()

  #create pressure label for title and value
  pressure_label = Label(window, text = 'Pressure', font =
  ('Helvetica', 18), anchor = S, width = 200, height = 2)
  pressure_label.pack()

  pressure = StringVar()

  pressure_value = Label(window, textvariable = pressure, font =
  ('Courier', 20), fg = 'green', anchor = N, width = 200)
  pressure_value.pack()

def update_readings():
      humidity.set(str(round(sense.humidity, 2)) + '%')
      humidity_bar.set(sense.humidity)
      temperature.set(str(round(sense.temperature, 2)) + '°C')
      #temperature.set(str(round(sense.temperature*(9/5)+32, 2))
  + '*F')
      pressure.set(str(round(sense.pressure)) + 'hPa')
      window.update_idletasks()
      window.after(3000, update_readings)

update_readings()
  window.mainloop()

As usual, you start the code by importing the necessary libraries . You may wonder why we need to import ttk if we’ve already imported everything with * from the tkinter library in the previous line. In this case, when you import with the wildcard *, you’re importing only a subset of what’s stored in the library folder—there isn’t any particular reason for this, it’s just the way the author of the library decided to do it—so we need to import the ttk library that’s also needed for this user interface separately.

To gather weather data, you need to use the physical Sense HAT and the sense_hat library.

Creating the User Interface

After importing all of the libraries, you implement the part of the code that creates the user interface. First, you create a window that’s 200×480 pixels and give it the title Local Weather Station . Then, you create a label for the humidity title with the settings shown in the table on page 131. At , you create a string variable called humidity that will hold the humidity value. This value is then displayed at .

The lines of code at create a canvas to place the progress bar in—the canvas is like a reserved space for the progress bar. After that, the code initializes a variable called humidity_bar of type double , which is the variable type accepted by the progress bar. Finally, the lines at create the humidity progress bar to place on the canvas.

The process for displaying titles and values for temperature and pressure follows the same steps as at , , and .

Automatically Updating the Readings

At , you define the update_readings() function, which updates the displayed values every three seconds to keep your weather readings up to date.

The following line updates the temperature variable:

temperature.set(str(round(sense.temperature, 2)) + '*C')

Let’s break this line into its component parts:

  • sense.temperature retrieves the temperature reading from the Sense HAT.
  • round(sense.temperature,2) rounds the temperature readings to two decimal places.
  • str(round(sense.temperature,2) converts the rounded reading to a string.
  • (str(round(sense.temperature,2)) + '*C') concatenates the degree symbol to the string.
  • temperature.set(str(round(sense.temperature, 2)) + '*C') updates the temperature variable with the latest reading.

The script uses a similar procedure for updating the pressure and humidity variables.

The window.update_idletasks() function keeps the window up to date while monitoring. Finally, window.after(3000, update_readings) adds update_readings as an event to the mainloop(), and tells the Pi to call this function every 3,000 milliseconds (3 seconds).

At , you call the update_readings() function and the window.mainloop() function that keeps the window running.

Finally, you can display the temperature in Fahrenheit by commenting and uncommenting these two lines:

#temperature.set(str(round(sense.temperature, 2)) + '*C')
temperature.set(str(round(sense.temperature*(9/5)+32, 2)) + '*F')

Running the Script

Press F5 or go to Run Run Module to run the script. You should see your weather data displayed in the user interface as shown at the beginning of the project.

Congratulations! You’ve made your own weather station. You are officially a budding meteorologist.

TAKING IT FURTHER

Here are some ideas for customizing this project:

  • Add the Fahrenheit conversion to the code and display the temperature as °F.
  • Change the graphical user interface—layout, font color, size, and type—to suit your tastes.
  • Use the LED matrix display on the Sense HAT to display information about the weather. For example, you can display text, relative bar graphs, or green and red arrows indicating temperature, humidity, or pressure rising or falling.
  • In the rest of the projects within this part, you’ll learn how to send an email with Python and how to save sensor readings. Use these skills to send your weather data to your email or build a weather station data logger. Make sure you don’t miss the next projects!
..................Content has been hidden....................

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