Temperature and humidity sensor

Before we go ahead and install the DHT library, we should first run the following command to ensure we have the latest versions of the setuptools, wheel and pip python packages.

sudo python3 -m pip install --upgrade pip setuptools wheel

Now using pip, we will go ahead and install Adafruit’s DHT library to the Raspberry Pi.

sudo pip3 install Adafruit_DHT


We will be using this Python library to interact with our DHT22 Humidity/Temperature sensor. Run the following command to install the DHT library to your Raspberry Pi.

Then you can install the MQTT client using pip with the command:

pip3 install paho-mqtt python-etcd


For the sensor implementation, first, download the repository (if not already done in IOT-1):

git clone https://github.com/GT-ARC/CC-IoT/


Note that the above command will create a local copy of all codes required in this batch of training modules (from IOT-1 to IOT-10). So you may skip the above step if you’ve already done it earlier.

For the current training module, browse to the directory “CC+IoT/7-8/” in your local repository.

The following code can be used for testing the sensor and getting experience with the sensors. Again we are using an MQTT communication protocol to transfer the data.


import Adafruit_DHT import time
import paho.mqtt.client as mqtt HOST = "test.mosquitto.org"
PORT = 1883
topic = "/test/temperature" client = mqtt.Client() client.connect(HOST, PORT)
# use the library to talk and interact with the DHT22 sensor. DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

while True:
    humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

    if humidity is not None and temperature is not None:
        print("Temperature={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity)) 
    else:
        print("Failed to retrieve data from humidity sensor")

    client.publish(topic, "Temperature={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity))

    time.sleep(2)

You can run the above code simply by calling the following command:

python temperature_sensor.py