Skip to content

Publish DHT sensor readings to MQTT broker

License

Notifications You must be signed in to change notification settings

farshidtz/dht-mqtt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DHT-MQTT

Read humidity and temperature measurements from a DHT11/DHT22 sensor connected to a Raspberry Pi and publish them to an MQTT broker.

It also supports the AM2302 sensor, which is the wired version of DHT22.

Run as a service

Requirement: Python 3, pip

Install

Install the CircuitPython-DHT library:

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

Configure and run as a service

  1. Clone and enter the directory
git clone xxx
cd dht-mqtt
  1. Create config.env

Copy from config.env.example.

Set the right values.

  • BROKER (string) is the MQTT broker's host name or IP address
  • BROKER_PORT (integer) is the MQTT broker's port
  • PIN (integer) is the GPIO pin number that the sensor data wire port is connected to. The python board module can be used to list available pins on the board. Learn more here.
  • SENSOR (string) is the sensor type. It should be either of: DHT11, DHT22, DHT21
  1. Run to test:
./run.sh
  1. Turn into a service

We use the dht-mqtt.service file to create the service. In the service file, the path for the run.sh script is set to /home/pi/dht-mqtt/run.sh. Modify the file to have the correct path and user.

Make a symbolic link to the service file:

sudo ln -s /home/pi/dht-mqtt/dht-mqtt.service /lib/systemd/system/dht-mqtt.service

Load the service file, enable (start on boot), and start now:

sudo systemctl daemon-reload
sudo systemctl enable --now dht-mqtt

Check the logs:

journalctl -u dht-mqtt -n 100 -f

Use systemctl restart dht-mqtt to load new configurations.

Run in a Docker container

WIP

docker run --privileged farshidtz/adafruit_dht [11|22|2302] GPIOpin#

For example to read from a DHT22 attached to GPIO4:

docker run --privileged farshidtz/adafruit_dht 22 4

Build Locally

docker build -t my_dht .