DHT11/DHT22 - temperature and humidity sensor

May i know that what is mean by" You will need to terminate the connection script
before uploading new sketches since it blocks access to the Serial port" because i just now try tutorial its work i able to upload dummy data to dashboard but now i cant upload the new sketch that just now you given

i can use this code already thanks tad but may i know that does the trigger function is down recently ?

1 Like

Yes

1 Like

if i want add gas sensor to this coding and i add this

"int analogValue = analogRead(A0);
int gas = map(analogValue, 0, 1023, 0, 100);
Cayenne.virtualWrite(3, gas, ā€œanalog_sensorā€, ā€œnullā€); "

below line of Cayenne.virtualWrite(2, event.relative_humidity, ā€œrel_humā€, ā€œpā€);
is this correct

Yes

May i know that how to change the word Analog in widget of gas sensor to percentage
i change the coding null to p also not changes

@laikuanyu94 have a look at this Data types for Cayenne MQTT API

2 Likes

Alright thanks

1 Like

Is that the the unit value inside the table is fix one or we change change it

i have never tried them interchanged but just made a simple example with this code:

Cayenne.virtualWrite(21, y, "analog_sensor", "p"); 
Cayenne.virtualWrite(22, y, "analog_sensor", "null");

but the change only can be seen in gauge widget and not in value widget. you can try diffferent combination.

I have my DHT11 working but Iā€™m a bit puzzled by some of the peaks and troughs which seem suspiciously large and sudden. Whatā€™s going on? Does it need some parameter tweeking? I donā€™t want to set up alarms and be getting false ones.

Hereā€™s an example:

UPDATE: Aha! I found the line with time.time in __init.py. Changed +2 to +10 and the graph already seems better. Time will tell if thatā€™s the solution.

LATER: No. Still getting these randoms huge peaks and troughs. Having done a bit more Googling, smoothing the data might be the only way forward. Itā€™s too late to look at it properly now: [SOLVED] DHT sensor occasionally returning spurious values - #5 by RobertLucian - GrovePi - Dexter Industries Forum

can you try this code and see if you are getting any spikes in the reading Overview | DHT Humidity Sensing on Raspberry Pi or Beaglebone Black with GDocs Logging | Adafruit Learning System

1 Like

Thanks, will check it out. Any thoughts as to which might be the best solution, yours or the one that I found? Iā€™m a little nervous of the dire warning on the former :slight_smile:

If I wanted to use this code, could I add it (bearing in mind mind Iā€™m a Python virgin)? If so where? By digital port, does it mean GPIO. Currently, mine is on port 11 (labelled 17 on the cobbler), so will this need changing to 7 in the code?

I guess, as my sensor is blue, I delete ā€˜white = 1 # The White colored sensor.ā€™?

import grovepi
import math
import numpy
import threading
from time import sleep
from datetime import datetime

sensor = 4  # The Sensor goes on digital port 4.
# temp_humidity_sensor_type
blue = 0    # The Blue colored sensor.
white = 1   # The White colored sensor.

filtered_temperature = [] # here we keep the temperature values after removing outliers
filtered_humidity = [] # here we keep the filtered humidity values after removing the outliers

lock = threading.Lock() # we are using locks so we don't have conflicts while accessing the shared variables
event = threading.Event() # we are using an event so we can close the thread as soon as KeyboardInterrupt is raised

# function which eliminates the noise
# by using a statistical model
# we determine the standard normal deviation and we exclude anything that goes beyond a threshold
# think of a probability distribution plot - we remove the extremes
# the greater the std_factor, the more "forgiving" is the algorithm with the extreme values
def eliminateNoise(values, std_factor = 2):
    mean = numpy.mean(values)
    standard_deviation = numpy.std(values)

    if standard_deviation == 0:
        return values

    final_values = [element for element in values if element > mean - std_factor * standard_deviation]
    final_values = [element for element in final_values if element < mean + std_factor * standard_deviation]

    return final_values

# function for processing the data
# filtering, periods of time, yada yada
def readingValues():
    seconds_window = 10 # after this many second we make a record
    values = []

    while not event.is_set():
        counter = 0
        while counter < seconds_window and not event.is_set():
            temp = None
            humidity = None
            try:
                [temp, humidity] = grovepi.dht(sensor, blue)

            except IOError:
                print("we've got IO error")

            if math.isnan(temp) == False and math.isnan(humidity) == False:
                values.append({"temp" : temp, "hum" : humidity})
                counter += 1
            #else:
                #print("we've got NaN")

            sleep(1)

        lock.acquire()
        filtered_temperature.append(numpy.mean(eliminateNoise([x["temp"] for x in values])))
        filtered_humidity.append(numpy.mean(eliminateNoise([x["hum"] for x in values])))
        lock.release()

        values = []

def Main():
    # here we start the thread
    # we use a thread in order to gather/process the data separately from the printing proceess
    data_collector = threading.Thread(target = readingValues)
    data_collector.start()

    while not event.is_set():
        if len(filtered_temperature) > 0: # or we could have used filtered_humidity instead
            lock.acquire()

            # here you can do whatever you want with the variables: print them, file them out, anything
            temperature = filtered_temperature.pop()
            humidity = filtered_humidity.pop()
            print('{},{:.01f},{:.01f}' .format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), temperature, humidity))

            lock.release()

        # wait a second before the next check
        sleep(1)

    # wait until the thread is finished
    data_collector.join()

if __name__ == "__main__":
    try:
        Main()

    except KeyboardInterrupt:
        event.set()

i could suggest to go with the simpler approach the one that i provided.

lets start with this:
on you raspberry install the following:

sudo apt-get update
sudo apt-get install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel
sudo pip3 install Adafruit_DHT
cd Adafruit_Python_DHT
sudo python3 setup.py install

Once done navigate to examples folder and open the sketch:
sudo nano Adafruit_Python_DHT/examples/simpletest.py

in the code you need to make the following changes:

sensor = Adafruit_DHT.DHT22
to
sensor = Adafruit_DHT.DHT11

# Example using a Beaglebone Black with DHT sensor
# connected to pin P8_11.
pin = 'P8_11'

# Example using a Raspberry Pi with DHT sensor
# connected to GPIO23.
#pin = 23

to

# Example using a Beaglebone Black with DHT sensor
# connected to pin P8_11.
#pin = 'P8_11'

# Example using a Raspberry Pi with DHT sensor
# connected to GPIO23.
pin = 17

you have connected your sensor to GPIO17. https://www.raspberrypi-spy.co.uk/wp-content/uploads/2012/06/Raspberry-Pi-GPIO-Layout-Model-B-Plus-rotated-2700x900.png

1 Like