I recently bought a RaspberryPi 4 and installed Ubuntu Server 20.04 64 Bit on it. There are many tutorials available how to read the temperature/humidity via Python, unfortunately none of them worked out of the box. It seems to be that they are
- either for Raspbian OS
- or for 32 Bit OSes.
After some searching I found a way from several sources to make it run. This is a horrible hacky workaround and I’d be very happy to see a better way and/or out-of-the-box solution.
Prerequisites
- Ubuntu Server 20.04.2 LTS
- Python 3 (preinstalled in aforementioned Ubuntu image)
- DHT11/DHT22 with 4 Pins connected to the Pi (follow this guide to see the wiring)
- dht.py (Source code from learn.adafruit.com)
Installation
1. Install Python 3 Pip
We will use adafruit-circuitpython-dht to read out the sensor and install it via pip
. Run below command from the shell.
|
|
2. Install RPi.GPIO
via apt-get
Usually this is a dependency to adafruit-circuitpython-dht
and thus could be installed with it. Unfortunately it does not succeed installing the dependency, so we need to install it ourself. For more information see this thread on askubuntu.com. Run below command from the shell.
|
|
3. Install adafruit-circuitpython-dht
|
|
4. Install libgiod
This step is a bit ugly. Basically the default installation did not succeed for me, and I ended up finding that this solution on GitHub worked yet slightly modified.
4.1. Install and build libgpiod
|
|
You should see a new folder named libgpiod_pulsein
. Run the script dht.py
(linked in the prerequisites) and you should see some similar error:
|
|
Of particular interest for us is the last line. The file exists, but Python cannot see/access it. Unfortunately granting Python any rights does not solve this problem either. So we need to replace it by the previous build and then grant python correct rights.
The path might be different on your computer, so don’t blindly copy & paste the next steps but in case it differs use path from your output.
4.2. Replace libgpiod
with build
Go into the directory libgpiod_pulsein/src/
from step 4.1. and run the following command from there (important: Replace the path if it differs).
|
|
4.3. Set suid
for Python
If you run dht.py
again, it will show you the same error as before. We need to allow any user to run python
with the same rights as the owner, which is root
. It is done via setuid. This solution was posted on armbian.com.
Please note: It is very dangerous to grant these rights to Python. So you should rather copy your Python Binary and change only the copy. See the linked solution for doing so.
As I have Python 3.8 on my machine, my Python Binary is found in /usr/bin/python3.8
. To enable setuid
, run the following command:
|
|
Read Sensor Data
Everything set up, so we are ready to read the data. You need to alter the script dht.py
in line 8
, depending on your GPIO Pin and Sensor:
|
|
It should now start without any errors and print output similar (different values) to that.
|
|