# Temperature and Humidity Monitoring Using DHT11 Sensor

In this project, you will be directed to monitor temperature and humidity using a **DHT11** sensor connected to a **Raspberry Pi**. Furthermore, the temperature and humidity data read by the **DHT11** sensor will be sent to the **Antares IoT Platform.**

## Prerequisites

The materials required follow the **General Prerequisites** on the previous page. If you have not prepared the requirements on that page, then you can visit the following page.

{% content-ref url="raspberry-gui-general-prerequisites" %}
[raspberry-gui-general-prerequisites](https://docs.antares.id/en/code-and-library-examples/raspberry-pi/gui-graphical-user-interface/raspberry-gui-general-prerequisites)
{% endcontent-ref %}

## Follow These Steps

### 1. Menyiapkan Peralatan

Here are some of the equipment you will need for temperature and humidity monitoring using the DHT11 Sensor:

* Raspberry Pi&#x20;
* Sensor DHT11
* Resistor 10kΩ
* Breadboard
* Jumper cables (3 jumper male to female and 3 jumper male to male)

{% hint style="info" %}
The **10kΩ resistor** is needed as a pull-up resistor used to stabilise the communication between the DHT11 sensor and the Raspberry Pi. This resistor is needed when you work with DHT11 sensors that have 4 pins.
{% endhint %}

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/WtSjIslToH3YI8v9cZER/1_Alat.png" alt=""><figcaption><p>Equipment Required for Temperature and Humidity Monitoring</p></figcaption></figure>

### 2. Assembling Hardware

For temperature and humidity monitoring, you need to connect the DHT11 sensor with the Raspberry Pi. You need to create a circuit as in the following image.

{% hint style="info" %}
Connect the DHT11 VCC pin to the Raspberry Pi's 3.3 V pin, the DHT11 GND pin to the Raspberry Pi GND pin, and the DHT11 data pin to the Raspberry Pi's GPIO 4. Finally, connect the end of the 10kΩ resistor to the DHT11 VCC pin and the other end to the DHT11 data pin.
{% endhint %}

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/Nw2dHgb47KNewPVjPxn2/2_Rangkaian.png" alt=""><figcaption><p>DHT11 to Raspberry Pi circuit</p></figcaption></figure>

Here is a pinout diagram of the Raspberry Pi and DHT11 sensor that can make it easier for you to build a circuit.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/eO5G1GQdJa17qY9XEurI/3_Pinout.png" alt=""><figcaption><p>Pinout Raspberry Pi</p></figcaption></figure>

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/BMMSnRlK6DpNMYCgrxy5/4_pinot%20sensor%20dht.jpg" alt=""><figcaption><p>Pinout Sensor DHT11</p></figcaption></figure>

### 3. Switching on the Raspberry Pi

To switch on the Raspberry Pi, insert the SD card that has the OS installed in the slot available on the Raspberry Pi board. Then connect the Raspberry Pi to the monitor using a Micro HDMI to HDMI cable. Also connect the keyboard and mouse to the USB slot on the Raspberry Pi as shown below. Finally, connect the Raspberry Pi board to the power source using USB-C.

{% hint style="info" %}
A powered-on Raspberry Pi will be signalled by an illuminated LED indicator near the USB-C port.
{% endhint %}

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/v9t69dp2BaK9Qaz9WNPm/1_Rangkaian%20alat.png" alt=""><figcaption><p>Connecting Raspberry Pi with Power Source and Monitor</p></figcaption></figure>

### 4. Switching on the Monitor and Opening the Terminal

After the Raspberry Pi is connected to the power source, then you can turn on the monitor. Raspberry Pi that has booted and entered the OS is shown as in the image below.

{% hint style="info" %}
If after switching on the monitor nothing appears on the screen, this means that the Raspberry Pi is booting the OS. You can wait a while until the GUI appears.
{% endhint %}

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/4UfnfbkQU8DNHj5zR539/2_GUI.png" alt=""><figcaption><p>GUI Raspberrry Pi</p></figcaption></figure>

Next, you can open the terminal on the top left as shown in the following icon image.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/s6aRCMQReNmsTeM0Fk72/3_Terminal.png" alt=""><figcaption><p>Terminal Icon Marked with Red Box</p></figcaption></figure>

The opened terminal will look like the following image.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/WahbfTbvqNbiaw0wfojv/4_Terminal%20Open.png" alt=""><figcaption><p>Terminal View on GUI</p></figcaption></figure>

### 5. Install Adafruit DHT11 Library

After assembling the hardware and turning on the Raspberry Pi via the monitor, you can open the terminal and install the DHT11 library from Adafruit by cloning from Github. The following syntax must be typed into the terminal.

```
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
```

After the cloning process is complete, the Adafruit\_Python\_DHT folder will appear, which can be checked by typing "ls" in the terminal.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/ttaKQZdU5TzWEJdJIqKL/1_Adafruit.png" alt=""><figcaption><p>Adafruit_Python_DHT folder that appears after the cloning process</p></figcaption></figure>

To install the DHT11 library, enter the Adafruit\_Python\_DHT folder by typing the following syntax.

```
cd Adafruit_Python_DHT
```

Once inside the folder, you can check the files inside by typing "ls" in the terminal.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/xDZlPWLNDkfPW2aLFiGC/2_cd%20Adafruit.png" alt=""><figcaption><p>Enter the Adafruit_Python_DHT Folder and Display the Folder Contents</p></figcaption></figure>

{% hint style="info" %}
In the terminal output above there is a setup.py file. This file is used to install the DHT11 library.
{% endhint %}

Type the syntax below to perform the installation.

```
sudo python setup.py install
```

After inputting the syntax above, the terminal output will be as shown below. In this condition, you have successfully installed the DHT11 library.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/mjUIP866TyY3zwEWTqDN/3_DHT%20Installation.png" alt=""><figcaption><p>Library DHT11 Installation</p></figcaption></figure>

### 6. Creating a Python File

After successfully installing the required libraries, you need to create a Python file to input the required programme code. You need to enter the examples directory by typing the following syntax.

```
cd examples
```

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/ET40sJhcc2lwTXlYXWNs/4_cd%20Examples.png" alt=""><figcaption><p>Enter the Examples Directory</p></figcaption></figure>

Then you need to create a new Python file by typing the syntax below.

```
sudo nano your-file-name.py
```

{% hint style="info" %}
You need to change **your-file-name** to your preferred filename.
{% endhint %}

After that, the display on the terminal will change to the one shown below.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/z5cTfAW0idKKLaIiQqKE/5_New%20Python%20File.png" alt=""><figcaption><p>Empty Python file for writing programme code</p></figcaption></figure>

{% hint style="info" %}
The display above shows an empty Python file ready to be input with programme code.
{% endhint %}

### 7. Inputting programme code

Here is the programme code that you need to input to the Python file that you created earlier.

{% code lineNumbers="true" %}

```python
import Adafruit_DHT
import time
import datetime
import requests

# Set DHT11 sensor type
sensor = Adafruit_DHT.DHT11

# Set GPIO pin where DHT11 sensor is connected
pin = 4

# Set Antares URL and headers
antares_url = 'masukkan URL'
headers = {
    'cache-control': 'no-cache',
    'content-type': 'application/json;ty=4',
    'x-m2m-origin': 'masukkan access-key'
}

while True:
    # Read data from DHT11 sensor
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    if humidity is not None and temperature is not None:
        print("Last valid input: " + str(datetime.datetime.now()))
        print("Temperature: %d C" % temperature)
        print("Humidity: %d %%" % humidity)

        # Create the data payload
        data = {
            "m2m:cin": {
                "con": "{\"Temperature\":%d,\"Humidity\":%d}" % (temperature, humidity)
            }
        }

        # Send the data to Antares
        try:
            response = requests.post(antares_url, headers=headers, json=data)
            response.raise_for_status()  # Check if the request was successful
            print('Data sent successfully.')
        except requests.exceptions.RequestException as e:
            print('Failed to send data:', e)

    else:
        print('Failed to get reading. Try again!')

    # Wait for 2 seconds before the next reading
    time.sleep(2)
```

{% endcode %}

{% hint style="info" %}
Don't forget to enter the device URL in the **antares\_url** section and the **access-key** in the **x-m2m-origin** section according to the Antares IoT Platform. Make sure there are no programme writing errors and pay attention to the indentation.
{% endhint %}

After successfully inputting the programme code, the display will be as shown below.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/FukRhsigJNZbFjtGUbvU/6_Python%20Code.png" alt=""><figcaption><p>Program Code that has been Inputted to Python File</p></figcaption></figure>

{% hint style="info" %}
After you have successfully inputted the programme code, next you need to save the Python file by pressing **Ctrl + X > Y > Enter**.
{% endhint %}

### 8. Executing Python Files

After the Node.js Request file has been successfully saved. Next you can execute the file by typing the following syntax in the terminal.

```
python your-file-name.py
```

{% hint style="info" %}
Don't forget to change **your-file-name** according to the name created earlier.
{% endhint %}

After the Python file is executed, the display on the terminal will be as shown below.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/VQRUib00P8PCsXKkYOLH/7_Code%20Execution.png" alt=""><figcaption><p>Terminal Output when Python FIle is Executed</p></figcaption></figure>

{% hint style="info" %}
The image above shows that the **DHT11 sensor** has been able to read the **temperature** and **humidity** data. The data has also been successfully sent to the Antares IoT Platform with the message **"Data sent successfully".**
{% endhint %}

### 9. Check Data on Antares IoT Platform

To ensure that the temperature and humidity data has been sent to the Antares IoT Platform, you can open your device URL. The following image shows the display on the Antares IoT Platform that has received data from the Raspberry Pi.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/iDk3Lhi1IKg4VmT5YxCc/monitoring%20RASP.png" alt=""><figcaption><p>Display on Antares IoT Platform that has Received Data from Raspberry Pi</p></figcaption></figure>
