Temperature control (DS18B20 + DHT22) with the Raspberry Pi

In order to know what’s happening inside a semi sealed box, i used a small piece of perf board and added the DHT22 and DS18B20 with 10k pullups. I also added a small push button for safely powering off the Pi if needed. It looks something like this:

My take on a temperature HAT for DS18B20 and DHT22

For this to work you need to install some dependencies.

sudo apt-get install python-dev 
sudo apt-get install python-pip 
sudo apt-get install git 
git clone https://github.com/adafruit/Adafruit_Python_DHT.git 
cd Adafruit_Python_DHT 
sudo python setup.py install 
pip install w1thermsensor

This basic code allows me to extract HR and Temperature values from the DHT connected to port 24 (DS18B20 is connected to GPIO23):

 

import sys
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
import urllib2

def getSensorData():
 RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 24)
 return (str(RH), str(T))
def main():
# print 'starting...'
 RH, T = getSensorData()
 print "Temp = ", int(float(T))," *C, Hum = ",int(float(RH))," %"

if __name__ == '__main__':
 main()

Sure i don’t want to connect every time. So i push the info to Thingspeak.

import sys
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
import urllib2
from w1thermsensor import W1ThermSensor

sensor = W1ThermSensor()

myAPI = "INSERT_YOUR_API_KEY_HERE"
def getSensorData():
 RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 24)
 return (str(RH), str(T))
def main():
 print 'starting...'
 baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
 RH, T = getSensorData()
 temperature_in_celsius = sensor.get_temperature()
 f = urllib2.urlopen(baseURL +
 "&field1=%s&field2=%s&field3=%s" % (RH, T, temperature_in_celsius))
 print f.read()
 f.close()

if __name__ == '__main__':
 main()

And i run the script every 30th minute of each hour via crontab.

30 *    * * *   root    python /home/pi/scripts/tempupload.py > /tmp/cron.out 2>&1

How does it look?

Like this.

Thingspeak

I take measurements every 30min. 1h should be enough but… why not?

 

What about GPIO shutdown?

It goes like this, connected to GPIO 22.

 

import RPi.GPIO as GPIO
import time
import os


GPIO.setmode(GPIO.BCM)
GPIO.setup(22, GPIO.IN, pull_up_down = GPIO.PUD_UP)


def Shutdown(channel):
    os.system("sudo shutdown -h now")

# Add our function to execute when the button pressed event happens
GPIO.add_event_detect(22, GPIO.FALLING, callback = Shutdown, bouncetime = 2000)

while 1:
    time.sleep(1)

1 thought on “Temperature control (DS18B20 + DHT22) with the Raspberry Pi”

Leave a Reply

Your email address will not be published. Required fields are marked *