Post

RPi IoT Project - Temperature and Humidity with DHT11 & InfluxDB

We are going to read Temperature and Humidity data from the DHT11 sensor, save it into an InfluxDB (say Hi to time-series DBs).

With that, you can feed the DHT sensor information to Home Assistant and let go your imagination.

All of this with docker as well? Yes, let’s put everything together and create a reliable Stack that we can share across any other RPi and forget about dependencies. Lets get to work.

Before Starting

  • Send DHT Data to InfluxDB
    • Hardware Check
    • Python Script
    • The Database: InfluxDB
  • Connect InfluxDB with DHT11 Data to Home Assistant (optional)

If you already have a RPi at home and a DHT11 sensor, you can perfectly get started with this project.

HardwareCodeData Analytics Stack
Raspberry Pi 4PythonInfluxDB
DHT11DockerfileHomeAssistant with InfluxDB Integration
WiresDocker-compose StackDocker Container

This is a mindmap of this IoT Project. All the code and configuration needed are in this post 👇

mindmap
  root((dht2influxdb))
    Software
      InfluxDB
      ::icon(fas fa-database)
      Python
      ::icon(fab fa-python)
        Adafruit_DHT Package
        InfluxDB Package
      Dockerfile
        Docker Compose Configuration
    Hardware
      Raspberry Pi 4
        DHT11 Temp Sensor
        ::icon(fas fa-thermometer-three-quarters)
        Three wires
    Tools
      Home Assistant
      Docker

We can use Raspberry Pi 32/64 bits for this project.

The Sensor: DHT11

Temperature and Humidity Data.

PinsDescription
+Connect 5V or 3.3V
dataTemp and Humidity data will be flowing here
-Ground (0V)

Connecting a DHT11 to a Raspberry Pi 4

To connect the sensor to the Raspberry, you can follow this schema:

Desktop View DHT11 connection to a Raspberry Pi 4

I prefer to use the 3.3V for the DHT11, and yet it will work perfectly with 5V as well.

In the RPi Official web you can find the original GPIO schema.

You can always go to the terminal and check with:

1
pinout

Why InfluxDB?

  • Performance: InfluxDB is designed to store and query time-series data quickly.
  • Scalability: InfluxDB can scale to handle large amounts of data.
  • Reliability: InfluxDB is a reliable database that is designed to keep your data safe.

And…InfluxDB is free and open source

The Base Code: Python with DHT11

Execute this code (it prints the values as well) to know that everything works for you, or just go to the next step point.

Credits to thegeekpub for the initial scheleton of the code.

I have adapted it so that instead of printing the values, it will push the Temperature and Humidity to an InfluxDB that we are going to self-host as well.

1
pip install Adafruit_DHT
  • And the library for the InfluxDB connection:
1
2
pip install influxdb
#pip show influxdb
  • This code will test that we get data and the the connections are working:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Adafruit_DHT
import time
from influxdb import InfluxDBClient

DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4

# Configure InfluxDB connection
#influx_client = InfluxDBClient(host='influxdb', port=8086)

# Try to create the database, or use it if it already exists
# database_name = 'sensor_data'
# existing_databases = influx_client.get_list_database()

# if {'name': database_name} not in existing_databases:
#     influx_client.create_database(database_name)
#     print(f"Database '{database_name}' created.")

#influx_client.switch_database(database_name)

while True:
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    if humidity is not None and temperature is not None:
        # data = [
        #     {
        #         "measurement": "dht_sensor",
        #         "tags": {},
        #         "time": time.strftime('%Y-%m-%dT%H:%M:%SZ'),
        #         "fields": {
        #             "temperature": temperature,
        #             "humidity": humidity
        #         }
        #     }
        # ]
        # influx_client.write_points(data)
        print("Data sent to InfluxDB:",humidity," ",temperature)
    else:
        print("Sensor failure. Check wiring.")
    time.sleep(3)

You can also check (uncommenting the influxDB part) if a local instance of the DB is recognizing the input data.

Pushing Data from Python to InfluxDB

The Python code and the InfluxDB can be running directly in our Raspberry Pi, but I prefer to use Docker containers when possible to isolate dependencies and make the projects more resilient and easier to debug.

The artifacts we need

Create an instance of the InfluxDB with Docker and this Docker-Compose:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
version: '3'
services:

  influxdb:
    image: influxdb:1.8
    container_name: influxdb
    ports:
      - "8086:8086"
    volumes:
      - influxdb_data:/var/lib/influxdb
    environment:
      - INFLUXDB_DB=sensor_data
      - INFLUXDB_ADMIN_USER=your_password
      - INFLUXDB_ADMIN_PASSWORD=change_me_please

volumes:
  influxdb_data:

We have 2 options for this to work:

Quick Setup

You have everything connected and want just a quick setup? Simply use this docker-compose below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
version: "3"
services:

  python_dht:
    container_name: python_dht
    image: fossengineer/dht11_python_to_influxdb  # Use the name of your pre-built Python image
    privileged: true
    environment:
      - INFLUXDB_HOST=influxdb
      - INFLUXDB_PORT=8086
      - INFLUXDB_DBNAME=sensor_data
      - INFLUXDB_USER=admin
      - INFLUXDB_PASSWORD=mysecretpassword
    command: ["python", "your_python_script.py"]

    depends_on:
      - influxdb

  influxdb: #this is running in other device, so make sure that the container is running before executing the python one
    image: influxdb:latest
    environment:
      - INFLUXDB_DB=sensor_data
      - INFLUXDB_ADMIN_USER=admin
      - INFLUXDB_ADMIN_PASSWORD=adminpass
      - INFLUXDB_USER=user
      - INFLUXDB_USER_PASSWORD=userpass    

FAQ

How can I Query InfluxDBs with SQL?

If you go inside the InfluxDB container, you can execute the following to check that everything is working as it should:

1
2
3
4
influx
show databases
use sensor_data
show measurements

Then, query your InfluxDB with:

1
2
SELECT * FROM dht_sensor
SELECT * FROM dht_sensor ORDER BY time DESC LIMIT 10

How can I install Home Assistant?

InfluxBD plays great with HomeAssistant, you can spin HA with this Docker-Compose:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
version: "2.1"
services:
  homeassistant:
    image: lscr.io/linuxserver/homeassistant:latest
    container_name: homeassistant
    network_mode: host
    environment:
      - PUID=1000
      - PGID=1000
      - TZ=Europe/Rome
    volumes:
      - ~/Docker/HomeAssistant:/config
    ports:
      - 8123:8123 #optional
    #devices:
    #  - /path/to/device:/path/to/device #optional
    restart: unless-stopped

You can also install HA as an OS in a RaspberryPi

The container will be exposed on port 8123, so you can access the Home Assistant web interface at http://localhost:8123

Integrating Home Assistant with InfluxDB

We can try: Settings - Devices and Services -> Add Integration -> InfluxDB

But in the latest versions of HA, you will get ‘This device cannot be added from the UI’.

Acces the HA container -> cd config -> cat configuration.yaml and you will have a look of its current content. We are going to modify with: vi configuration.yaml

Make it look like this one below (we are adding our influxDB credentials):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
default_config:

# Load frontend themes from the themes folder
frontend:
  themes: !include_dir_merge_named themes

automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

influxdb:
  host: YOUR_INFLUXDB_HOST
  port: YOUR_INFLUXDB_PORT
  username: YOUR_INFLUXDB_USERNAME
  password: YOUR_INFLUXDB_PASSWORD
  database: YOUR_INFLUXDB_DATABASE #sensor_data

To apply: Esc + :w to save Esc + :q to exit

Why priviledge flag?

The container needs access to the GPIO port, otherwise, you will observe this error in the container:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Traceback (most recent call last):

  File "dht11_python_timescale.py", line 34, in <module>

    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)

  File "/usr/local/lib/python3.8/site-packages/Adafruit_DHT/common.py", line 81, in read

    return platform.read(sensor, pin)

  File "/usr/local/lib/python3.8/site-packages/Adafruit_DHT/Raspberry_Pi_2.py", line 34, in read

    raise RuntimeError('Error accessing GPIO.')

RuntimeError: Error accessing GPIO.

HA Integrations

You can check more HA integrations in the official page.

We have used the InfluxDB integration in this post, but there are much more:

When buyind Iot devices, check that their integration is classified as local push or local polling to avoid dependencies with 3rd Party clouds.

Both are great to create a fully local IoT Home.

HACS - Non Official Integrations

You can find them here: https://hacs.xyz/

HA add-ons

HA Add-ons are different concept than integrations.

Check them here: https://community.home-assistant.io/tag/hassio-repository

Remember that Add-ons are only available if you’ve used the Home Assistant Operating System or Home Assistant Supervised installation method.

This post is licensed under CC BY 4.0 by the author.