How to Drive DHT sensor without Library


 Let's code! Expalantions are in the code area. Happy Coding!

/*
 * DHT 11 driving without library
 * 
 * http://en.devrelerim.com
 * Author : Hakan OZMEN (hakkanr@gmail.com)
 * Date   : 30.03.2021
 * 
 * You can change or share all / or same part of
 * this code. Free of charge! :) 
 */

uint8_t data[5]; // to save our 8bit * 5 data
void setup() {
Serial.begin(115200);
}
/*
 *  This function count an 8bit integer value
 *  while given signal is not changed
 *  no need to measure time counting is also
 *  need time ;)
 */
uint8_t expectedSignal(bool level)
{
  uint8_t count=0;
  while(digitalRead(2) == level) count++;
  return count;
}
void loop() {
delay(2000); // wait 2 secs for sensor to initialize
Serial.println("----------------------"); 
 pinMode(2, INPUT_PULLUP); // Standard is HIGH
 delay(1000);
 pinMode(2, OUTPUT); // make pin 2 output
 digitalWrite(2, LOW);  // send LOW to sensor to wake up
 delay(18); // wait sensor to wake up time is A1 to A2
 pinMode(2, INPUT_PULLUP); // this also make pin HIGH an input state wait sensor data
 uint32_t tmp = expectedSignal(HIGH); // we wait sensor to make signal high again.
 tmp = expectedSignal(LOW);  //
 tmp = expectedSignal(HIGH);  // PRESENCE section
 uint8_t signals[80]; // to keep counts 
 for(uint8_t i = 0; i<80; i+=2) // we need 40 bits then steps 2
 {
  signals[i] = expectedSignal(LOW);  // there are low signals also
  signals[i+1] = expectedSignal(HIGH);  // our HIGH state signals
 }
 for (uint8_t a = 0; a<5; a++)  // 5 times to 5 sets of data
{
  for (uint8_t i=0; i<16; i+=2)  // 16/2 times to 8bits of data
  {
    Serial.print(a*16 +i);
    Serial.print(". bit LOW count :");
    Serial.print(signals[a*16 +i]);
    Serial.print(" HIGH count :");
    Serial.println(signals[a*16 +i +1]);
    data[a] <<= 1;   // Left shift to store new bit at last digit, it is 0 default
    if(signals[16 * a + i] < signals[16*a+i+1]) data[a] |= 1;// HIGH bit then send 1 to last bit
  }
  Serial.print("data in this bits: ");Serial.println(data[a]);
}
Serial.print("Humi: ");
Serial.print(data[0]);
Serial.print(".");
Serial.print(data[1]);
Serial.print("% Temp: ");
Serial.print(data[2]);
Serial.print(".");
Serial.print(data[3]);
Serial.println(" degrees");
}




// Happy Coding!




<- Previous Part Analysis of DHT11 wave form

Comments

Popular posts from this blog

How does P10 Led Panel Work? | Working Principle and calculations

Working Principle of DHT Sensors and Analysis with Logic Analyzer