Gnashock
Posts: 9
Joined: Wed May 06, 2015 7:00 pm

DHT22/AM2302

Wed May 06, 2015 7:54 pm

I just wanted to start making experience with the DHT22/AM2302 (a temperature and humidity sensor), but I have no idea how to initialize and get the data of it ... I tried to use GpioPin:

Code: Select all

gpioController = GpioController.GetDefault();
if(gpioController == null)
{
    Debug.WriteLine("GpioController Initialization failed.");
    return;
}
sensorPin = gpioController.OpenPin(7);
sensorPin.SetDriveMode(GpioPinDriveMode.Input);
Debug.WriteLine(sensorPin.Read());
but get the exception: "A resource required for this operation is disabled."

After that I took a look at the library for the unixoids and found this:

https://github.com/technion/lol_dht22/b ... er/dht22.c

But I have no idea how to realize that in VCSharp using Windows 10, anyone an idea or experience?

Thank you very much in advance!

jtanner_msft
Posts: 105
Joined: Fri May 01, 2015 7:12 pm

Re: DHT22/AM2302

Wed May 06, 2015 10:24 pm

While it doesn’t include the exact same sensor chip models that you’ve referenced, we do have a sample that shows how to hook up a temperature and force sensor to a RPi2 device:
http://microsoft.hackster.io/windowsiot ... sor-sample

Hopefully it can serve as a starting point for you with interacting with your sensor.
Jonathan Tanner | Microsoft | Windows 10 IoT Core Insider Preview Support | This posting is provided 'as is' with no warranties and confers no rights.

pbrwr
Posts: 22
Joined: Tue Sep 04, 2012 9:03 pm
Location: The Netherlands

Re: DHT22/AM2302

Thu May 07, 2015 6:33 pm

I'm working on a wrapper class for that sensor. When it's done i'll post a link to it. It can take a while, as I first have force a display into submission.

Gnashock
Posts: 9
Joined: Wed May 06, 2015 7:00 pm

Re: DHT22/AM2302

Thu May 07, 2015 8:05 pm

pbrwr wrote:I'm working on a wrapper class for that sensor. When it's done i'll post a link to it. It can take a while, as I first have force a display into submission.
This sounds very great, Im looking forward to that!

thambi
Posts: 1
Joined: Fri May 08, 2015 4:15 am

Re: DHT22/AM2302

Fri May 08, 2015 4:20 am

I am also facing same issue . please check the URL
https://msdn.microsoft.com/en-us/library/dn960157.aspx

We will get the error if PIN is reserved by system.

jtanner_msft
Posts: 105
Joined: Fri May 01, 2015 7:12 pm

Re: DHT22/AM2302

Sat May 09, 2015 12:03 am

Have you verified you're adding the using reference for the Windows.Devices.Gpio namespace?
Also I don't see in your code that you're checking to see if you got a valid Pin reference. For a very simple GPIO example please check out this sample:

http://ms-iot.github.io/content/win10/s ... Blinky.htm
Jonathan Tanner | Microsoft | Windows 10 IoT Core Insider Preview Support | This posting is provided 'as is' with no warranties and confers no rights.

Gnashock
Posts: 9
Joined: Wed May 06, 2015 7:00 pm

Re: DHT22/AM2302

Sat May 09, 2015 10:50 am

I really was using the wrong GPIO-Pin-Port, because the GpioPin 7 does not exist, but using the right Pin of it, results as value just HIGH, but the Sensor Output should be more complex, so I tried to use this as template: http://microsoft.hackster.io/windowsiot ... sor-sample

But using the SPI just goes a little step forward, because I have to restart the Raspberry Pi 2 every time, I want to start my app for testing purposes, otherwise the device will not be found, furthermore Im not sure how to get the right values from it, so lets share the current Code:

Code for initialization of the SpiDevice

Code: Select all

private async void InitSPI()
        {
            try
            {
                var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
                settings.ClockFrequency = 500000;
                settings.Mode = SpiMode.Mode0;

                string spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME);
                var deviceInfo = await DeviceInformation.FindAllAsync(spiAqs);
                SpiDisplay = await SpiDevice.FromIdAsync(deviceInfo[0].Id, settings);
            }
            catch(Exception ex)
            {
                Debug.WriteLine("SPI Initialization failed: " + ex.Message);
            }
        }
Code for trying to read the data, according to the C-Library found here:
https://github.com/technion/lol_dht22/b ... er/dht22.c

Code: Select all

private string ToValue()
        {
            string retString = "";

            uint laststate = 1;
            uint counter = 0;
            uint j = 0, i;

            int[] dht22_dat = new int[5]{ 0, 0, 0, 0, 0 };

            byte[] buffer = new byte[1];

            int MAXTIMINGS = 85;

            for (i = 0; i < MAXTIMINGS; ++i)
            {
                counter = 0;
                while (sizecvt(read()) == laststate)
                {
                    ++counter;
                    if (counter == 255)
                    {
                        break;
                    }
                }

                laststate = sizecvt(read());

                if (counter == 255) break;

                if ((i >= 4) && (i % 2 == 0))
                {
                    dht22_dat[j / 8] <<= 1;
                    if (counter < 16)
                    {
                        dht22_dat[j / 8] |= 1;
                    }
                    ++j;
                }
            }
            if ((j >= 40) && dht22_dat[4] == ((dht22_dat[0] + dht22_dat[1] + dht22_dat[2] + dht22_dat[3]) & 0xFF))
            {
                float t, h;
                h = (float)dht22_dat[0] * 256 + (float)dht22_dat[1];
                h /= 10;
                t = (float)(dht22_dat[2] & 0x7F) * 256 + (float)dht22_dat[3];
                t /= 10;
                if((dht22_dat[2] & 0x80) != 8) t *= -1;

                retString = String.Format("Humidity = {0} && Temperature = {1]", h, t);
                return retString;
            }
            else
            {
                retString = "Data not good, skip";
                return retString;
            }
        }

        private int read()
        {
            byte[] buffer = new byte[1];
            SpiDisplay.Read(buffer);
            return (int)buffer[0];

        }

        private uint sizecvt(int read)
        {
            if(read > 255 || read < 0)
            {
                Debug.WriteLine("Invalid data");
                return 0;
            }
            return (uint)read;
        }
But I just get "Data not good, skip"

jtanner_msft
Posts: 105
Joined: Fri May 01, 2015 7:12 pm

Re: DHT22/AM2302

Mon May 11, 2015 10:14 pm

Please keep in mind that the first sample you've referenced is in C#, and the second lib that you're using was written in C. So there could be some language incompatibilities happening because of that alone.

Did the first part initialize the SPI device without any errors though?
Jonathan Tanner | Microsoft | Windows 10 IoT Core Insider Preview Support | This posting is provided 'as is' with no warranties and confers no rights.

tomfitzphilly
Posts: 8
Joined: Thu Jan 11, 2018 2:40 am

Re: DHT22/AM2302

Sun Apr 29, 2018 5:57 pm

Here's a short python script to run multiple DHT22s and dump the data to a MySQL database for multiple location monitoring.

It uses Joan's pigpio library and modified sensor code.

Code: Select all

#!/usr/bin/python
# By tomfitzphilly - use as you will at your own risk.
# I run this from cron @reboot in the background using pigpiod
# to run pigpio as a service see 
# https://github.com/joan2937/pigpio/tree/master/util
# Adapted from script by JOAN @ abyz.me.uk GIThub joan2937 using
# Joan's pigpio and DHT22 libraries (copyright and license unknown)
# and Obi Wan who could care less as long as you don't blame him.
# Dumps data to a mySQL or Maria DB

import os
import sys
import socket
import time
os.system("sudo gpiod") # if pigpio is not run as a service
time.sleep(3)


import glob
import MySQLdb
import DHT22 as S
import atexit
import pigpio as pi

box = pi.pi()
s = S.sensor(box, 18)#Sensor pin (optional LED pin = **, power = **)
r = 0
next_reading = time.time()
INTERVAL = 1800 #Seconds between readings must be > 2 - should be 900

while True:
	r += 1
	s.trigger()
	time.sleep(5) #wait for the reading to come back
	name = 'your master name' # house, lake_house, etc
	location = 'location within name' # Basement, Office, etc
	cTemp = s.temperature()
	temp = (cTemp * 9 / 5) + 32
	humidity = s.humidity()
	# next two lines for testing
	# Print to screen
	# print("{} {} {}".format(r, temp, humidity))
	
	myDB = MySQLdb.connect(host="DB Host IP",port=3306,user="user",passwd="password",db="database")
	cur = myDB.cursor()

	try:
		query = "INSERT INTO `testdata`(`Name`, `Location`, `T-Reading`, `H-Reading`)VALUES (%s, %s, %s, %s)"
		cur.execute(query, (name, location, temp, humidity))
		myDB.commit()
		# for testing print ("Commit Sucessful")
	except (MySQLdb.Error, MySQLdb.Warning) as e:
		print(e)

	next_reading += INTERVAL
	
	time.sleep(next_reading - time.time())# Overall INTERVAL second polling.

	s.cancel()
	pi.stop()
	os.system("sudo killall pigpio") #if pigpio is not run as a service

User avatar
DougieLawson
Posts: 38883
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: DHT22/AM2302

Sun Apr 29, 2018 6:05 pm

tomfitzphilly wrote:
Sun Apr 29, 2018 5:57 pm
Here's a short python script to run multiple DHT22s and dump the data to a MySQL database for multiple location monitoring.

It uses Joan's pigpio library and modified sensor code.
Does MySQL work on Win10 IoT?
Does Joan's pigpio work on Win10 IoT?

Here's a clue: NO!
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

Return to “Windows 10 for IoT”