I’ve gotten the DHT22 temperature-humidity sensor working using a modified version of the code posted by @wgbartley (https://community.spark.io/t/dht22-dht11-and-similar-blocking-version/998 ). I’ve also looked at the pulse lengths using a variation of that program that uses a 1 microsecond delay and a counter inside the while loop (rather than using micros() as below). I was trying to do a similar thing using micros() to get a more accurate view of the pulse lengths, but I get bizarre readings that I can’t make sense of. Here is the code I’m using,
int dataPin = D4;
void setup() {
Serial.begin(19200);
pinMode(dataPin, OUTPUT);
digitalWrite(dataPin, HIGH);
read();
}
void loop() {
}
void read(void) {
noInterrupts();
for (int k = 0; k<4; k++) {
delay(3000);
uint8_t lastState = HIGH;
uint8_t j = 0, i;
unsigned long results[85];
uint8_t state[85];
unsigned long t0 = 0;
unsigned long t1 = 0;
Serial.println("");
Serial.println("started!");
pinMode(dataPin, OUTPUT);
digitalWrite(dataPin, HIGH);
delay(250);
digitalWrite(dataPin, LOW);
delay(20);
digitalWrite(dataPin, HIGH);
delayMicroseconds(40);
pinMode(dataPin, INPUT);
// read in timings
for (i=0; i< 85; i++) {
t0 = micros();
while (digitalRead(dataPin) == lastState) {
t1 = micros();
if ((t1 - t0) > 1000)
break;
}
lastState = digitalRead(dataPin);
results[i] = t1 - t0;
state[i] = lastState;
if ((t1 - t0) > 1000)
break;
}
for (j=0; j< 85; j++) {
delay(2);
Serial.print(j);
delay(2);
Serial.print(" ");
delay(2);
Serial.print(results[j]);
delay(2);
Serial.print(" ");
delay(2);
Serial.print(state[j]);
delay(2);
Serial.print(" ");
delay(2);
Serial.println("");
delay(2);
}
}
Serial.println("");
Serial.println("");
Serial.println("Ending serial");
interrupts();
Serial.end();
}
I print out the index of the loop, the time difference in microseconds (t1 - t0), and the state of the pin. Here is a sample of the results,
started!
0 4279527169 0
1 0 0
2 16 0
3 536871520 0
4 134257971 0
5 536879020 0
6 1073756172 0
7 536871520 0
8 16 124
9 16 78
10 0 0
11 128 32
12 0 3
13 0 16
14 0 0
15 12288 0
16 0 177
17 16 31
18 536879030 0
19 16 32
20 536877892 124
21 536879020 78
22 1 0
23 536891300 32
24 134248479 77
25 536877892 122
Given the code, the time difference should never be bigger than 1000, and the pin state should be either 0 or 1. As you can see, the time difference values are sometimes as large as 9 figures, and the pin state, while sometimes 0, is never 1, and frequently some other number. Interestingly, the numbers are not random – I run the loop 4 times, and I get the same printout each time. Is there something wrong wight he way I’m using micros()?