Wednesday 30 December 2020

Set up humidity and temperature sensor on Rasp Pi

 Having just purchased a new dehumidifier, I wanted to keep a check on the humidity in the property. I have couple of Raspberry Pi's spare so decided it would be a good idea to use these along with the DHT11 sensor. The sensor can be bought reasonably cheaply.

Set up of the sensor is really simple - I bought a pack of 5 from Amazon, I don't know how accurate with regard to humidity they are, but figured once I get a few readings I can work out the ideal time to remotely switch on the dehumidifier. For me the actual humidity was not as important as to the pattern the humidity was following.

There are 3 pins out on the sensor I bought, they are marked quite clearly, main thing to remember is the pin used for the data - I went for pin number 7, or gpio pin 4. 

I wanted to make the setup as small as possible so used a Pi 0, also wanted to use up a couple of 2gb cards I've had for ages, which really are to small and slow for much now - however by using the Raspberry Pi OS lite from here I managed to get everything working on the 2gb disk, with room to spare!!

I set up using ssh

To set up python3 and pip and the adafruit_dht library I followed instruction from this page;
https://github.com/adafruit/Adafruit_Python_DHT
sudo apt update
sudo apt install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel
Then install the Adafruit_DHT library
sudo pip3 install Adafruit_DHT
Now to install python3 rpi.gpio control
sudo apt install python3-dev python3-rpi.gpio
I struggled with receiving the data in a useable form until after many searches I came upon;
https://electronut.in/dht11-rpi-cloud-plot/ 
this did exactly what I required, it was easy to set up and I could view the results online from wherever I happened to be. Thank you so much for taking the time to share it.

I've changed the code slightly, you need to make sure you put the correct pin number in this line;

 RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4) Pin number is the last number here.
Also original script stopped if the internet connection went down, I've changed it so that the program sleeps for a while then rechecks again. 
I've also set the time for each reading at 10 minutes, this is shown at the sleep(600) change the number to suit your own needs

"""

dht11_thingspeak.py

Temperature/Humidity monitor using Raspberry Pi and DHT11.
Data is displayed at thingspeak.com

Author: Mahesh Venkitachalam
Website: electronut.in

"""

import sys
import RPi.GPIO as GPIO
from time import sleep  
import Adafruit_DHT
import urllib.request, urllib.error, urllib.parse

def getSensorData():
    RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4)
    # return dict
    return (str(RH), str(T))

# main() function
def main():
    # use sys.argv if needed
    if len(sys.argv) < 2:
        print('Usage: python tstest.py PRIVATE_KEY')
        exit(0)
    print('starting...')

    baseURL = 'https://api.thingspeak.com/update?api_key=%s' % sys.argv[1]

    while True:
        try:
            RH, T = getSensorData()
            f = urllib.request.urlopen(baseURL +
                                "&field1=%s&field2=%s" % (RH, T))
            print(f.read())
            f.close()
            sleep(600)
        except:
            sleep(300)
            

# call main
if __name__ == '__main__':
    main()

That is most of it set up, you need to visit Thingspeak to set up your channels there, once you've done that go back to your pi and at the command prompt do;
 sudo python3 dht11_thingspeak.py YOURWRITEAPIKEY 
As I have ssh'd in, it will stop when I close the connection, so I used the nohup to keep it alive;
 sudo nohup python3 dht11_thingspeak.py YOURWRITEAPIKEY
To ensure the sensor is almost always on, I put a line in crontab so on reboot the script starts automatically
sudo crontab -e
scroll to last line and paste
@reboot sleep 200 && nohup /usr/bin/python3 /home/pi/dht11_thingspeak.py YOURWRITEAPIKEY
I found it would only work if I put the whole address in.

You can view the results of your sensor at

https://api.thingspeak.com/channels/YOUR_CHANNEL_ID



The only snag with the original code is that it's written in Python2 which is being stopped, although I got it working, I eventually used 2to3 to convert the original code to python3. 
sudo apt install 2to3
then point at your file and 
2to3 -w my_file.py 
this will overwrite the original file.