Temperature Sensors on a Raspberry Pi hosting Domoticz
June 25, 2017
Updated: January 2, 2018
-- Temperature Sensors - Take 2->

Reading device specifications before purchasing them might just be a good idea. Turns out that the DHT11 temperature and humidity sensor has a 0°C to 50°C temperature range. This is definitely not acceptable for an installation in an unheated garage where temperatures in the winter often dip below freezing point. So the DHT11 I purchased for an intelligent garage door monitor will be replaced with a DHT22 (AM2302) which has a much wider temperature range of -40°C to 80°C.

It would be a waste to discard a $1.25 CDN sensor. Why not install it on the Raspberry Pi in the living room hosting my home automation system? It will then be possible to access it in Domoticz and eventually keep a temperature and humidity log.

There are plenty of descriptions on the Web on how to do this. But most assume that the default One-Wire GPIO pin will be used. Unfortunately, it is covered (but not used!) by the real-time clock installed on the same Raspberry Pi (see Real Time Clock, DS3231, for Domoticz on the Raspberry Pi). Further searches on the Web revealed that the problem is easily solved without resorting to any hardware modification.

While at it, I decided to monitor the Raspberry Pi temperature. This seems particularly useful when overclocking the system.

Table of Contents

  1. Enabling 1-Wire
  2. Installing the Adafruit DHTxx Python Library
  3. Installing a Temperature Sensor in Domoticz
  4. Python Script
  5. CPU Temperature
  6. Temperature Monitoring

  1. Enabling the 1-Wire interface
  2. The DHT11 and the DHT22/AM2302 temperature and humidity sensors communicate using the 1-Wire communication bus system. This is actually a three-wire connection, ground and power are needed in addition to the data line.

    It seems that it is no longer necessary to modify the file /boot/config.txt. See my latest blog related to this topic: Removing Nuisance Messages in Raspberry Pi Syslog. It is not clear if raspi-config should be invoked at all.
    January 2, 2018

    The 1-wire interface can be enabled with the raspi-config utility. However, it will only enable the 1-Wire interface on the default BCM 4 pin (physical pin 7). It is necessary to edit the config.txt in the /boot directory to use a different GPIO pin. Add a line at the end of the file or modify the dtoverlay=w1-gpio line if 1-wire is already enabled. I decided to use the BCM 24 (18 pĥysical) pin for a 1-wire data pin.

    pi@domo:~ $ sudo nano /boot/config.txt
    ... dtoverlay=w1-gpio, gpiopin=24

    I chose BCM 24 because it has adjacent 3.3V and ground pins which simplifies the connection.

         3v3 power [17][18] BCM 24 - 1-wire
     BCM 10 (MOSI) [19][20] Ground

    Since this is a modification of config.txt, 1-wire will be enabled on the next boot. Impatient persons may enable it immediately

    pi@domo:~ $ sudo modprobe w1-gpio gpiopin=24
    but this is a temporary situation and 1-wire will not be enabled on BCM 24 automatically on the next reboot without the change to config.txt described above.

    Note: While the DHT series of sensors use the 1-wire communication protocol, they are not Dallas One Wire compatible. What that means is that each DHT sensor must have a dedicated data pin. Multiple sensors may not be connected in parallel on a 1-wire bus.

    Reference: W1-GPIO - One-Wire Interface.

  3. Installing the Adafruit DHTxx Python Library
  4. Adafruit has developed four libraries to communicate with DHT series sensors. I used the Python library. Both git and the Python development package are needed to install it. The version control software was already installed on my Raspberry Pi; I think git is installed in Raspbian.

    pi@domo:~ $ sudo apt-get install build-essential python-dev pi@domo:~ $ git clone pi@domo:~ $ cd Adafruit_Pyt* pi@domo:~/Adafruit_Python_DHT $ sudo python install

    Once the library has been installed, it is possible to test that everything works interactively. Here is an example run.

    pi@domo:~ $ python Python 2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Adafruit_DHT >>> print(, 24)) (None, None) >>> print(, 24)) (None, None) >>> print(, 24)) (50.0, 24.0) >>> print(, 24)) (None, None) >>> exit() pi@domo:~ $

    As can be seen, the read function can return (None, None). A possible explanation for this failure is that an interval of at least 2 seconds between access to the DHT11 is necessary. The library provides a function, read_retry, that will try up to 15 times to read the sensor's data waiting 2 seconds between each try. These default values can be changed.

    Reference: How to Set Up the DHT11 Humidity Sensor on the Raspberry Pi.

  5. Installing a Temperature Sensor in Domoticz
  6. It's now time to create a virtual temperature+humidity sensor in Domoticz. The first step, if not already done, is to create a "dummy" hardware. Then a virtual sensor will be added to the hardware. Finally, the sensor values will be modified with the JSON API to make sure everything works.

    To add virtual hardware

    1. Click on the Setup tab.
    2. Select Hardware in the drop-down menu.
    3. Enter a name for the hardware; I chose Virtual.
    4. For the Type select Dummy (Does nothing, use for virtual switches only) in the drop-down list.

    5. Add virtual hardware
    6. Click on the Add button. The added hardware will be added in a table at the top of the page:
      This step is done only once.

    To add a virtual sensor

    1. Click on the Create Virtual Sensors in the newly created Virtual hardware.
    2. Fill in the Name field, select Temp+Hum for Sensor Type in the Create Virtual Sensor window:
      A message will pop up confirming the creation of the sensor and stating that it can be found in the devices' list.
    3. To see the device list, click on the Setup tab and then select Devices.

      Note the virtual sensor idx number. It will be needed later on.


    1. Display the newly created sensor by clicking on the Temperature tab. If that tab is not visible on the Web interface then
      1. Click on Setup tab.
      2. Click on Settings in the drop-down menu
      3. Scroll down to the bottom of the  System  page in order to see Active Menus:
      4. Check Temperature.
      5. Scroll up to the top of the page and click on  Apply Settings .
      6. Click on the Temperature tab which should now be visible.
    2. The sensor image will appear as shown on the left.
    3. Open a Web browser and enter the following address and JSON string;76.7;1 If there is no problem the status on the returned page should be "OK"

      and, after a short delay, the sensor image should now reflect the new temperature, humidity and humidity level.

      Instead of using a Web browser, an MQTT message can be sent assuming that the MQTT hardware has been installed in Domoticiz.

      michel@hp:~$ mosquitto_pub -h "domoticz/in" -m '{ "idx" : 35, "nvalue" : 1, "svalue" : "21.2;76.7;1"}'

  7. Python Script
  8. A python script can read the sensor data using the Adafruit python DHT library and send on the values to Domoticz.

    pi@domo:~ $ mkdir pythons pi@domo:~ $ cd pythons pi@domo:~/pythons $ nano
    #!/usr/bin/python import sys import Adafruit_DHT import urllib # parameters DHT_type = 11 OneWire_pin = 24 sensor_idx = 35 url_json = "" verbose = 1 # set to 1 to print out information to the console # read dht11 temperature and humidity humidity, temperature = Adafruit_DHT.read_retry(DHT_type, OneWire_pin) # use Domoticz JSON url to update cmd = url_json + str(sensor_idx) + "&nvalue=0&svalue=" + str(temperature) + ";" + str(humidity) + ";0" hf = urllib.urlopen(cmd) if verbose > 0: print 'Sensor data: temperature = {0:0.1f}C, humidity = {1:0.1f}%'.format(temperature, humidity) print 'Uploaded to Pi: ' + cmd print 'Response: ' + hf.close
    Download the file by clicking on the link with the right mouse button.

    This is just a first draft, so we will not bother making it executable. But it can be tested easily.

    pi@domo:~/pythons $ python Sensor data: temperature = 24.0C, humidity = 48.0% Uploaded to Pi:;48.0;0 Response: { "status" : "OK", "title" : "Update Device" }

    Note the trailing ";0" in the JSON url. It is the value of the HUM_STAT (humidity status?) parameter. Its possible values are 0 to 3.

        0 = Normal
        1 = Comfortable
        2 = Dry
        3 = Wet
    To the right of each value is the string displayed in the first line of the sensor on the Temperature tab.

    Looking over Web offerings, it seems most either systematically set HUM_STAT to 0 as in the above script or else calculate a value using the relative humidity:

    if humidity > 70: HUM_STAT = 3 elif humidity > 30: HUM_STAT = 1 else: HUM_STAT = 2

    The latter approach is not the best. To quote the National Weather Service of the US National Oceanic and Atmospheric Administration "if you want a real judge of just how "dry" or "humid" it will feel outside, look at the dew point instead of the [relative humidity]. The higher the dew point, the muggier it will feel." While I doubt the correctness of the grammar, I trust NOAA's judgement on using the dew point instead of the relative humidity to qualify the perception of dryness. I will take up this question later on.

  9. CPU temperature
  10. The Raspberry Pi has a built-in thermal sensor and reports the current CPU temperature on a regular basis. The measure is written to a file; listing its content shows that the temperature is reported in thousandths of Celsius degree.

    pi@domo:~ $ cat /sys/class/thermal/thermal_zone0/temp 42236

    The CPU temperature is thus 42.236°C (or 108.025°F).

    It also possible to use the vcgencmd utility to get a formatted temperature reading.

    pi@domo:~ $ vcgencmd measure_temp temp=42.2'C

    It is fairly easy to write a python script to read this value and send it on to be displayed in a temperature sensor in Domoticz. Creating a temperature sensor is the same as creating the temperature and humidity sensor as described above except for the sensor type.

    #!/usr/bin/python import sys import urllib # parameters cpu_idx = 36 url_json = "" verbose = 1 # set to 1 to print out information to the console # read cpu temperature # replace 1000.0 with 1000 to round to nearest degree cpuTemp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1000.0 # use Domoticz JSON url to update cmd = url_json + str(sensor_idx) + "&nvalue=0&svalue=" + str(cpuTemp) hf = urllib.urlopen(cmd) if verbose > 0: print 'Sensor data: temperature = {0:0.1f}C'.format(cpuTemp) print 'Uploaded to Pi: ' + cmd print 'Response: ' + hf.close
    Download the file by clicking on the link with the right mouse button.

    [Tutorial] Show RPI's Temperature with a command.
    RPI vcgencmd usage.

  11. Temperature Monitoring
  12. The two scripts presented above are easily merged into a single python script that will be executed at regular intervals by cron. Here is the script

    #!/usr/bin/python # coding: utf-8 import sys import Adafruit_DHT import urllib # parameters DHT_type = 11 OneWire_pin = 24 room_temp_idx = 35 cpu_temp_idx = 36 url_json = "" verbose = 1 # 1 to print out information to the console, 0 for silence # read and report dht11 temperature and humidity humidity, temperature = Adafruit_DHT.read_retry(DHT_type, OneWire_pin) cmd = url_json + str(room_temp_idx) + "&nvalue=0&svalue=" + str(temperature) + ";" + str(humidity) + ";0" hf = urllib.urlopen(cmd) if verbose > 0: print 'Données lues: température ambiante {0:0.1f}°C, humidité {1:0.1f}%'.format(temperature, humidity) print 'URL JSON pour Domoticz: ' + cmd print 'Réponse: ' + hf.close # read and report cpu temperature cpuTemp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3 cmd = url_json + str(cpu_temp_idx) + "&nvalue=0&svalue=" + str(cpuTemp) hf = urllib.urlopen(cmd) if verbose > 0: print 'Donnée lue: température du Raspberry Pi: {0:0.1f}°C'.format(cpuTemp) print 'URL JSON pour Domoticz: ' + cmd print 'Réponse: ' + hf.close
    Download the file by clicking on the link with the right mouse button (The script was updated on July 4, 2017).

    The second line, # coding: utf-8 is the only significant change. It was necessary because French messages will be printed to the console (if verbose is set equal to 1) and these contain Unicode characters. That second line can be removed if only ASCII characters are used in the python script.

    I saved the script under the name and verified that it worked.

    pi@domo:~/pythons $ python Données lues: température ambiante 23.0°C, humidité 53.0% URL JSON pour Domoticz:¶m=udevice&idx=35&nvalue=0&svalue=23.0;53.0;0 Réponse: { "status" : "OK", "title" : "Update Device" } Donnée lue: température du Raspberry Pi: 42.8°C URL JSON pour Domoticz:¶m=udevice&idx=36&nvalue=0&svalue=42.774 Réponse: { "status" : "OK", "title" : "Update Device" }

    That means also checking the sensors in Domoticz were updated.

    Since everything worked, I changed the verbose flag to 0, and made the file executable and added an entry in the cron schedule.

    pi@domo:~/pythons $ sudo chmod +x pi@domo:~/pythons $ crontab -e
    # m h dom mon dow command # update Domoticz temperature and humidty sensors every 5 minutes */5 * * * * /home/pi/pythons/ exit the editor saving the changes crontab: installing new crontab

    After a while, the logged data accumulated by Domoticz can be viewed in a graph and saved to a file. Click on the Log button on the temperature sensor.

    You need not worry that a precipitous cold snap occurred at the start of the summer. The big fluctuations in the temperature and humidity levels in the late evening of the 27th are "fake news" that I created to see how the calculated dew point changed in response.

    This post is getting long. I will look into further use of the temperature sensors in the next post.

-- Temperature Sensors - Take 2->