DHT22 Issues

Hello from a total newb to Arduino and forum. I was wodering if anyone could point me in the direction of working code for a DHT22 on the M0.
I have an arduino M0 Pro and bought 2 DHT22 sensors. My main issue is the software I think... I only managed to get one version of code to actually compile and upload and that was an old Adafruit code. I modified the output code slightly to get a more detailed view of what was going on. Sadly my output from this code seemed rather odd and output was the same for both sensors and does not change when I breath on the sensor

Failed to read from DHT sensor!
Humidity is: nan
Temp is: -3276.70
Temp true is: -5866.06

I have also tried code on your site posted by Rob Tillaart and hiss code on github : Arduino/libraries/DHTstable at master · RobTillaart/Arduino · GitHub but to no avail - it will not compile

In file included from C:\Program Files (x86)\Arduino\hardware\arduino\samd\cores\arduino/delay.h:27:0,
                 from C:\Program Files (x86)\Arduino\hardware\arduino\samd\cores\arduino/Arduino.h:70,
                 from dht.h:19,
                 from dht.cpp:41:
dht.cpp: In member function 'int8_t dht::_readSensor(uint8_t, uint8_t, uint8_t)':
C:\Program Files (x86)\Arduino\hardware\arduino\samd\variants\arduino_zero/variant.h:64:82: error: invalid conversion from 'PortGroup*' to 'uint8_t {aka unsigned char}' [-fpermissive]
 #define digitalPinToPort(P)        ( &(PORT->Group[g_APinDescription[P].ulPort]) )
dht.cpp:120:20: note: in expansion of macro 'digitalPinToPort'
     uint8_t port = digitalPinToPort(pin);
C:\Program Files (x86)\Arduino\hardware\arduino\samd\variants\arduino_zero/variant.h:69:44: error: base operand of '->' is not a pointer
 #define portInputRegister(port)    ( &(port->IN) )
dht.cpp:121:29: note: in expansion of macro 'portInputRegister'
     volatile uint8_t *PIR = portInputRegister(port);
dht.cpp:163:51: error: 'min' was not declared in this scope
                 zeroLoop = min(zeroLoop, loopCount);
Error compiling.

Looking forward to some pointers to some code or a solution

Failed to read from DHT sensor!

And yet nothing changes when you breathe on it. I'm shocked, I tell you.

The code that you actually used was NOT part of your post.
A link to the library that you actually used was not part of your post.
A schematic was not part of your post.

Looking forward to some pointers to some code or a solution

Keep looking.

@PaulS Am I right in saying that from your response I'm either not following the correct protocol of etiquette for this forum or you are in a very vague way saying you'd prefer a little more information? Please clarify and I'll accommodate where possible...

or you are in a very vague way saying you'd prefer a little more information?

I didn't think there was anything vague in my post.

If you had read the stickies at the top of the forum, you'd have noticed that you MUST post code when posting in this section of the forum.

If you haven't read the stickies, then you ARE violating protocol.

Your code uses some libraries. We need to know EXACTLY which ones. You tell us that by posting a link (using the link icon, not just be pasting in a URL).

You have the hardware connected somehow. You show us exactly how by posting a schematic. Hand-drawn is fine.

Clearly I’m in violation and the moment I locate said stickies I’ll read them.
OK I have a M0 Pro, with a DHT22 connected to it directly. The DHT22 came complete, mounted on a small board (picture attached)
I have the DHT connected to the M0 Pro Grd → Grd, VCC to 5V and dat->pin DIGITAL PWM pin 2

ino code

#include "DHT.h"
#define DHTPIN 2     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
#define fan 4

int maxHum  = 60;
int maxTemp = 40;


void setup(){
    pinMode(fan, OUTPUT);

void loop(){
    // Wait a few seconds between measurements.
    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius
    float t = dht.readTemperature();
    float f = dht.readTemperature(true);
    // Check if any reads failed and exit early (to try again).
   if (isnan(h) || isnan(t) || isnan(f)) {
   Serial.println("Failed to read from DHT sensor!");
   Serial.print("Humidity is: ");
   Serial.print("Temp is: ");
   Serial.print("Temp true is: ");
    if  (t > maxTemp || h > maxHum){
        digitalWrite(fan, HIGH);
         digitalWrite(fan, LOW); 
    Serial.print("Humidity: "); 
    Serial.print(" %\t");
    Serial.print("Temperature: "); 
    Serial.println(" *C ");


/* DHT library 

MIT license
written by Adafruit Industries

#include "DHT.h"

DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
  _pin = pin;
  _type = type;
  _count = count;
  firstreading = true;

void DHT::begin(void) {
  // set up the pins!
  pinMode(_pin, INPUT);
  digitalWrite(_pin, HIGH);
  _lastreadtime = 0;

//boolean S == Scale.  True == Farenheit; False == Celcius
float DHT::readTemperature(bool S) {
  float f;

  if (read()) {
      switch (_type) {
            case DHT11:
                f = data[2];
                f = convertCtoF(f);
                return f;
            case DHT22:
            case DHT21:
                f = data[2] & 0x7F;
                f *= 256;
                f += data[3];
                f /= 10;
                if (data[2] & 0x80)
          	f *= -1;
          	f = convertCtoF(f);
              return f;
  return NAN;

float DHT::convertCtoF(float c) {
	return c * 9 / 5 + 32;

float DHT::convertFtoC(float f) {
  return (f - 32) * 5 / 9; 

float DHT::readHumidity(void) {
  float f;
  if (read()) {
      switch (_type) {
            case DHT11:
                 f = data[0];
                 return f;
            case DHT22:
            case DHT21:
                 f = data[0];
                 f *= 256;
                 f += data[1];
                 f /= 10;
                 return f;
  return NAN;

float DHT::computeHeatIndex(float tempFahrenheit, float percentHumidity) {
  // Adapted from equation at: https://github.com/adafruit/DHT-sensor-library/issues/9 and
  // Wikipedia: http://en.wikipedia.org/wiki/Heat_index
  return -42.379 + 
           2.04901523 * tempFahrenheit + 
          10.14333127 * percentHumidity +
          -0.22475541 * tempFahrenheit*percentHumidity +
          -0.00683783 * pow(tempFahrenheit, 2) +
          -0.05481717 * pow(percentHumidity, 2) + 
           0.00122874 * pow(tempFahrenheit, 2) * percentHumidity + 
           0.00085282 * tempFahrenheit*pow(percentHumidity, 2) +
          -0.00000199 * pow(tempFahrenheit, 2) * pow(percentHumidity, 2);

boolean DHT::read(void) {
  uint8_t laststate = HIGH;
  uint8_t counter = 0;
  uint8_t j = 0, i;
  unsigned long currenttime;

  // Check if sensor was read less than two seconds ago and return early
  // to use last reading.
  currenttime = millis();
  if (currenttime < _lastreadtime) {
    // ie there was a rollover
    _lastreadtime = 0;
  if (!firstreading && ((currenttime - _lastreadtime) < 2000)) {
    return true; // return last correct measurement
    //delay(2000 - (currenttime - _lastreadtime));
  firstreading = false;
    Serial.print("Currtime: "); Serial.print(currenttime);
    Serial.print(" Lasttime: "); Serial.print(_lastreadtime);
  _lastreadtime = millis();

  data[0] = data[1] = data[2] = data[3] = data[4] = 0;
  // pull the pin high and wait 250 milliseconds
  digitalWrite(_pin, HIGH);

  // now pull it low for ~20 milliseconds
  pinMode(_pin, OUTPUT);
  digitalWrite(_pin, LOW);
  digitalWrite(_pin, HIGH);
  pinMode(_pin, INPUT);

  // read in timings
  for ( i=0; i< MAXTIMINGS; i++) {
    counter = 0;
    while (digitalRead(_pin) == laststate) {
      if (counter == 255) {
    laststate = digitalRead(_pin);

    if (counter == 255) break;

    // ignore first 3 transitions
    if ((i >= 4) && (i%2 == 0)) {
      // shove each bit into the storage bytes
      data[j/8] <<= 1;
      if (counter > _count)
        data[j/8] |= 1;


  Serial.println(j, DEC);
  Serial.print(data[0], HEX); Serial.print(", ");
  Serial.print(data[1], HEX); Serial.print(", ");
  Serial.print(data[2], HEX); Serial.print(", ");
  Serial.print(data[3], HEX); Serial.print(", ");
  Serial.print(data[4], HEX); Serial.print(" =? ");
  Serial.println(data[0] + data[1] + data[2] + data[3], HEX);

  // check we read 40 bits and that the checksum matches
  if ((j >= 40) && 
      (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
    return true;

  return false;


And the dht.h

#ifndef DHT_H
#define DHT_H
#if ARDUINO >= 100
 #include "Arduino.h"
 #include "WProgram.h"

/* DHT library 

MIT license
written by Adafruit Industries

// how many timing transitions we need to keep track of. 2 * number bits + extra
#define MAXTIMINGS 85

#define DHT11 11
#define DHT22 22
#define DHT21 21
#define AM2301 21

class DHT {
  uint8_t data[6];
  uint8_t _pin, _type, _count;
  unsigned long _lastreadtime;
  boolean firstreading;

  DHT(uint8_t pin, uint8_t type, uint8_t count=6);
  void begin(void);
  float readTemperature(bool S=false);
  float convertCtoF(float);
  float convertFtoC(float);
  float computeHeatIndex(float tempFahrenheit, float percentHumidity);
  float readHumidity(void);
  boolean read(void);


The above code compiles and gives me the readings I supplied in my first post.
If there is any further information anyone requires please let me know.
I have no knowledge of Arduino, the IDE or C so your tolerance and understanding would be apprciated

Thanks in advance


Don't know if it matters but you're comparing "ints" to floats, try changing:

int maxHum  = 60;
int maxTemp = 40;


float maxHum  = 60.0;
float maxTemp = 40.0;

Thanks outsider, for a quick response. I don’t believe it should make any difference but its not my code. The only change I made was to the Serial.print lines. Naive of me perhaps, but I assumed that this code should work correctly as its probably been used by hundreds of people. I have changed to float and it makes no difference… the result is the same.

Can you post a link to the Arduino that you have? I do not see an M0 listed on the Arduino products page.

As requested

You might have noticed that this is NOT the arduino.org site. If not, perhaps you should.