This looks similar to what I did with a DHT11 temperature sensor with first a Raspberry Pi 3 and then with an Arduino.
The Arduino code is at this URL: https://github.com/RichardChambers/anduino_uno/blob/master/project01/dht11_sensor.ino
One thing that I did was to write the DHT11 function, onewireReadDHT11()
in my source code, so that I could collect statistics on how the read function was working. What I found was that the counter
value check needed to be around 25 for a Raspberry Pi 3. However for an Arduino the comparison value was much less. You may need to increase that value to more than 30 for a Raspberry Pi.
So an edited version of your read_dht11_dat()
function with the if
statement modified follows. The if
statement checks the value of the variable counter
which is really the width of the pulse received.
One thing you can do is to print the actual data received out as hex values and check that if the dht11_dat[]
data is all zeros or all ones.
void read_dht11_dat() {
uint8_t laststate = HIGH;
uint8_t counter = 0;
uint8_t j = 0, i;
float f;
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
pinMode(DHTPIN, OUTPUT);
digitalWrite(DHTPIN, LOW);
delay(18);
digitalWrite(DHTPIN, HIGH);
delayMicroseconds(40);
pinMode(DHTPIN, INPUT);
for (i = 0; i < MAXTIMINGS; i++) {
counter = 0;
while(digitalRead(DHTPIN) == laststate) {
counter++;
delayMicroseconds(1);
if (counter ==255) break;
}
laststate = digitalRead(DHTPIN);
if (counter == 255)
break;
if ((i >= 4) && (i % 2 == 0)) {
dht11_dat[j/8] <<= 1;
if (counter > 25) // this check is how long the pulse width is low.
dht11_dat[j/8] |= 1;
j++;
}
}
if ((j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF ))) {
f = dht11_dat[2] * 9. / 5. + 32;
printf("Humidity = %d.%d %% Temperature = %d.%d C (%.1f F)\n",
dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f);
} else {
printf("Data not good, skip \n");
}
}