Raspberry Pi Tutorial: Weather Station

Introduction

The Raspberry Pi Weather Station is constructed by connecting a temperature & humidity sensor and a servo motor to the Raspberry Pi to sense and indicate the temperature of its surrounding.

In this tutorial, we explain how to build a Weather Station with Raspberry Pi, a temperature & humidity sensor, a servo motor, and a Python program.

 

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. Temperature Humidity Sensor DHT22/AM2302
  5. Servo Motor SG92R 180°
  6. Raspberry Pi 5.5" HDMI Capacitive Touch AMOLED + Case 1080×1920 (optional)
  7. 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!

Temperature Humidity Sensor DHT22/AM2302

This Temperature Humidity Sensor DHT22 uses a capacitive humidity sensor, and a thermistor to measure the surrounding air temperature. The result is available via a digital signal on the data pin. What is good about the digital signal is that the signal will not decay over long distances.

Servor Motor SG92R 180°

This micro servo can rotate approximately 180 degrees (90 in each direction). You can use any servo code, hardware, or library to control these servos. Good for beginners who want to make stuff move without building a motor controller with feedback & gearbox, especially since it will fit in small places.

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

Connect the Temperature & Humidity Sensor to the corresponding GPIO pins on the Raspberry Pi. There are 3 pins on the Temperature & Humidity Sensor, namely, the VCC (Power Supply), Data (outputs temperature and humidity data), and ground. Connect these pins to the corresponding GPIO pins for 3V3 power, GPIO 4, and Ground on the Raspberry Pi. 

The Raspberry Pi will be receiving temperature and humidity data from the Temperature & Humidity Sensor via GPIO 4.

Connect the Servo Motor to the corresponding GPIO pins on the Raspberry Pi. There are 3 pins on the Servo Motor, namely, the VCC (Power Supply), PWM Signal, and ground. Connect these pins to the corresponding GPIO pins for 3V3 power, GPIO 24, and Ground on the Raspberry Pi. 

The Raspberry Pi will be modulating pulses to turn the servo via GPIO 24.

The wiring diagram below shows the connections between the Raspberry Pi, the Temperature & Humidity Sensor, and the Servo Motor.

Print the Scale and Indicator overlay. Cut the Scale overlay and paste it on a table or wall where you wish to display the temperature. Cut the Indicator overlay and paste it on the arm of the servo motor.

 

Setting up the Software

Power on the Raspberry Pi. Run the terminal from the taskbar and type the following commands to install the CircuitPython DHT library:

pip3 install adafruit-circuitpython-dht
sudo apt-get install libgpiod2

 

Coding the Weather Station Program

Let's start coding our weather station project. We will be coding this program in Python. Open "Thonny Python IDE".

# import libraries
import RPi.GPIO as GPIO
import board
import adafruit_dht
from time import sleep

The lines of codes import all the required libraries for this project.

# declare pin
servoPin = 24

The pins for the DHT22 Temperature & Humidity Sensor is initialized at GPIO pin 4# create dht object

# create dht object
dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)

The pins for the DHT22 Temperature & Humidity Sensor is initialized at GPIO pin 4

# set to use Broadcom GPIO numbers
GPIO.setmode(GPIO.BCM)

# disable warnings
GPIO.setwarnings(False)

# set servo pin as output
GPIO.setup(servoPin, GPIO.OUT)

# initialize PWM on pin at 50Hz
pwm = GPIO.PWM(servoPin, 50)

# start pwm with 0 duty cycle so it doesn't set any angles on start
pwm.start(0)

The pins are initialized and are now ready to receive data from the Temperature & Humidity Sensor and to send data to the Servo Motor.

# create function so we can call this later
def Set_Angle(angle):
   # calculate duty cycle from angle
   duty = angle / 18 + 2

   # turn on servo pin
   GPIO.output(servoPin, True)

    # set duty cycle to pin
   pwm.ChangeDutyCycle(duty)

    # wait 1s for servo to move into position
   sleep(1)

    # turn off servo pin
   GPIO.output(servoPin, False)

    # set duty cycle to 0 to stop signal
   pwm.ChangeDutyCycle(0)

Create a Set Angle function so we can call this method in our code later. Instead of having to perform calculations every time we want to set the servo angle, we create a method so we can get all the calculations done by just calling the method.

# main loop
while True:
   try:
       # Print the values to the serial port
       temperature_c = dhtDevice.temperature
       temperature_f = temperature_c * (9 / 5) + 32
       humidity = dhtDevice.humidity
       print("Temp: {:.1f} F / {:.1f} C    Humidity: {}% ".format(temperature_f, temperature_c, humidity))

       if temperature_c <= 29:
           Set_Angle(165)
       elif temperature_c <= 30:
           Set_Angle(135)
       elif temperature_c <= 31:
           Set_Angle(105)
       elif temperature_c <= 32:
           Set_Angle(75)
       elif temperature_c <= 33:
           Set_Angle(45)
       elif temperature_c <= 34:
           Set_Angle(15)
   except RuntimeError as error:
       # Errors happen fairly often, DHT's are hard to read, just keep going
       print(error.args[0])
       continue

    except Exception as error:
       dhtDevice.exit()
       raise error

   sleep(1)

Read the sensor and set the servo angle accordingly. The DHT22 Temperature & Humidity Sensor will return an error once in a while – this is normal. Wait for a second before polling the sensor again to ensure data is refreshed.

# stop pwm on exit
pwm.stop()

# release GPIOs on exit
GPIO.cleanup()

Clear the PWM and release the GPIOs on program exit to free up resources.

Run the program, notice that the Raspberry Pi is reading and displaying the temperature and humidity of its surrounding, and printing it to the console.

Based on the temperature read from GPIO4, the Raspberry Pi sends a corresponding instruction to the servo motor to turn its arm.

 

Resources