การใช้ DHT22 กับ ESP32 และ ESP8266

สวัสดีครับ

วันนี้นำเอาเรื่องราวที่เป็นปัญหาสำหรับการเริ่มต้นเล่น  อุปกรณ์พื้นฐาน  เช่น  ESP32  ESP8266 กับ DHT11, DHT22, AM2315, AM2310

ที่ดูเหมือนจะง่ายเอา เข้าจริงๆ ก็วุ่นวายทีเดียว   กระทั่งได้คำตัวก็เอามาแชร์กันครับ

ข้อแตกต่างข้อแรก  คือ การเรียกใช้ WiFi ของ  ESP8266 กับ ESP32  คนละตัวกัน

  • ESP8266 ก็ให้ใช้  #include <ESP8266WiFI.h>  ตามปกติ
  • ESP32     ก็ให้ใช้  #include <WiFI.h>  และไปปิดคอมเม้นท์  //#include <ESP8266WiFi.h>

ข้อแตกต่างถัดไปคือการเรียกใช้  DHT library

  • #include <Adafruit_Sensor.h>
  • #include <DHT.h> // กรณีนี้ต้องใช้คู่กันกับ DHT_U.h
  • #include <DHT_U.h>

และ  เลือกใช้กันให้ถูกต้อง

  • //#define DHTTYPE  DHT11 // DHT 11
  • #define DHTTYPE   DHT22 // DHT 22 (AM2302)
  • //#define DHTTYPE   DHT21 // DHT 21 (AM2301)

และ

  • DHT_Unified dht(DHTPIN, DHTTYPE);
  • //DHT dht(DHTPIN,DHTTYPE);
  • uint32_t delayMS;

ตามตัวอย่าง  ก็ลองสืบหา  library กันดูนะครับ

และตรวจสอบเรื่อง  ขา  กันให้เรียบร้อย  ก็เป็นอันว่าสำเร็จ

สำหรับ code อื่นๆ นั้นจะยาวหน่อยเป็นส่วนของการวัดน้ำฝน  และการเชื่อมต่อกับ Server

ลองๆ กันดูนะครับ  ทักทายสอบถามได้ทาง  Inbox facebook ครับ

/*
 *  This sketch sends data via HTTP GET requests to data.sparkfun.com service.
 *
 *  You need to get streamId and privateKey at data.sparkfun.com and paste them
 *  below. Or just customize this script to talk to other HTTP servers.
 *  Set board NodeMCU-32S pr ESP32 Dev Module
 *  Set Programmer AVRISP mkll
 */
//===== AM2301 - DHT21 setting
// Unified Sensor Library Example
// Written by Tony DiCola for Adafruit Industries
// Released under an MIT license.

// Depends on the following Arduino libraries:
// - Adafruit Unified Sensor Library: https://github.com/adafruit/Adafruit_Sensor
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// Use 3V3 GIOP 2 ESP32 Dev Module 
// Programmer AVRSIP mkll

#include <ESP8266WiFi.h>
//
#include <Adafruit_Sensor.h>
#include <DHT.h>  // กรณีนี้ต้องใช้คู่กันกับ  DHT_U.h
#include <DHT_U.h>

#define DHTPIN 2 // Pin which is connected to the DHT sensor.

// Uncomment the type of sensor in use:
//#define DHTTYPE           DHT11     // DHT 11 
#define DHTTYPE           DHT22     // DHT 22 (AM2302)
//#define DHTTYPE           DHT21     // DHT 21 (AM2301)

// See guide for details on sensor wiring and usage:
//   https://learn.adafruit.com/dht/overview

DHT_Unified dht(DHTPIN, DHTTYPE);
//DHT dht(DHTPIN,DHTTYPE);
uint32_t delayMS;

//=========
//#include <WiFi.h>  // for ESP32 
//======

 //====

const char* ssid     = "Arsenal2019_2.4G";
const char* password = "kb756992xxxxx12";

const char* host = "otrixiot.com";
const char* code = "SRC-Wxxxxx";
const char* dID = "9xxx2";
float temp_0 = 0;
float humid_0 = 0;
float vHumidity = 0;
float vTemperature = 0;
float data1=33;
float data2=33;
float data3=0; // rainsensor value
float data4=100;
float data5=33;
float data6=33;
float data7=33;
float data8=33;
float data9=33;
float data10=33;
float data11=33;
float data12=33;
float data13=33;
float data14=33;
float data15=33;
float data16=33;
float data17=33;
float data18=33;
float data19=33;
float data20=33;

/// rain sensor
int RainSensorPin = A0;    // select the input pin for the potentiometer
int RainSensorValue = 0;  

///

/*
void setup_Sensor_Box_Temperature()
{
  dht.begin();
}
*/
/// ===
void DHT_setup() {
  Serial.begin(115200); 
  // Initialize device.
  dht.begin();
  
}

void AM2301_setup() {
  Serial.begin(115200); 
  // Initialize device.
  dht.begin();
  Serial.println("DHTxx Unified Sensor Example");
  // Print temperature sensor details.
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.println("Temperature");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" *C");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" *C");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" *C");  
  Serial.println("------------------------------------");
  // Print humidity sensor details.
  dht.humidity().getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.println("Humidity");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println("%");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println("%");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println("%");  
  Serial.println("------------------------------------");
  // Set delay between sensor readings based on sensor details.
  delayMS = sensor.min_delay / 1000;
}


// Main setup ========
void setup()
{
    Serial.begin(115200);
    //DHT_setup();      
    AM2301_setup();
    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

int value = 0;

void loop()
{
    delay(5000);
    //DHT_loop();
    AM2301_loop();
//    scanSensor_Box_Temperature();
    //data1 = vTemperature;
    ++value;
    data1 = temp_0;
    data2 = humid_0;
    Serial.print("connecting to ");
    Serial.println(host);
    Rain_loop();
    Serial.print("Rain ... mm  ");Serial.println(data3);
    // Use WiFiClient class to create TCP connections
    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }

    // We now create a URI for the request
     String url = "/api/insertData?device_id=" + String(dID)+"&code="+String(code)+"&data1=" +String(data1) +"&data2="
   + String(data2)+"&data3=" +String(data3)+"&data4=" +String(data4)+"&data5=" +String(data5)
   +"&data6=" +String(data6)+"&data7=" +String(data7)+"&data8=" +String(data8)+"&data9=" +String(data9)
   +"&data10=" +String(data10)+"&data11=" +String(data11)+"&data12=" +String(data12)+"&data13=" +String(data13)
   +"&data14=" +String(data14)+"&data15=" +String(data15)+"&data16=" +String(data16)+"&data17=" +String(data17)
   +"&data18=" +String(data18)+"&data19=" +String(data19)+"&data20=" +String(data20);   
 
    Serial.print("Requesting URL: ");
    Serial.println(url);

    // This will send the request to the server
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
    unsigned long timeout = millis();
    while (client.available() == 0) {
        if (millis() - timeout > 5000) {
            Serial.println(">>> Client Timeout !");
            client.stop();
            return;
        }
    }

    // Read all the lines of the reply from server and print them to Serial
    while(client.available()) {
        String line = client.readStringUntil('\r');
        //Serial.print(line);
    }

    Serial.println();
    Serial.println("closing connection");
    delay(50000);
}
//====
/*
void DHT_loop() {
  // Delay between measurements.
  delay(2000);

  // 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 (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  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!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
  temp_0 = t;
  humid_0 = h;
  
}
*/
void Rain_loop() {
  // read the value from the sensor:
  RainSensorValue = analogRead(RainSensorPin);
   // stop the program for <sensorValue> milliseconds:
  data3 = RainSensorValue*50/1023;
}
//====
void AM2301_loop() {
  // Delay between measurements.
  delay(delayMS);
  // Get temperature event and print its value.
  sensors_event_t event;  
  dht.temperature().getEvent(&event);
  if (isnan(event.temperature)) {
    Serial.println("Error reading temperature!");
  }
  else {
    Serial.print("Temperature: ");
    Serial.print(event.temperature);
    Serial.println(" *C");
    temp_0 = event.temperature;
  }
  // Get humidity event and print its value.
  dht.humidity().getEvent(&event);
  if (isnan(event.relative_humidity)) {
    Serial.println("Error reading humidity!");
  }
  else {
    Serial.print("Humidity: ");
    Serial.print(event.relative_humidity);
    Serial.println("%");
    humid_0 = event.relative_humidity;
  }
  
}

และอีก โค้ดสำหรับ  ESP32 กับ  DHT22  ที่ต้องใช้  library  DHTesp.h   ดู  #include <DHTesp.h>

#include <DHTesp.h>

//#include "DHT.h"

#define DHTPIN 5
#define DHTTYPE DHT22

DHTesp dht(DHTPIN,DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

 

1,630 total views, 6 views today