氣象站建置

Posted on Sat, Mar 5, 2022 氣象站
How to show the temperature and humidity of your room on a Heltec WiFi Kit 32 attached to a DHT11 / DHT22 sensor - Techcoil Blog

When you have a DHT11 / DHT22 sensor, you can measure the temperature and humidity of your room. If you attach the sensor to a Heltec WiFi Kit 32 development board, you will be able to put up the readings on a 0.96 Inch OLED screen.

改為使用 heltec wireless stick lite 開發板,同樣使用 DHT11 作為感測器,不過新增了由溫濕度推算而得的舒適溫度和露點,也改用 C++ 實作。

原始碼:

#include <WiFi.h>
#include "ThingSpeak.h"
#include "DHTesp.h"
#include <Adafruit_Sensor.h>

//#define DHTPIN GPIO22

const char* ssid = "SSID";   
const char* password = "PASSWORD";   

WiFiClient  client;

unsigned long myChannelNumber = 1;
const char * myWriteAPIKey = "XXXX";

// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;

// Variable to hold temperature readings
float temp;
float humid;
float heat_index;
float dew_point;


// Create a sensor object
DHTesp dht;


void setup() {
  Serial.begin(115200);  //Initialize serial
  dht.setup(22, DHTesp::DHT11);
  
  WiFi.mode(WIFI_STA);   
  
  ThingSpeak.begin(client);  // Initialize ThingSpeak
}

void loop() {
  if ((millis() - lastTime) > timerDelay) {
    
    // Connect or reconnect to WiFi
    if(WiFi.status() != WL_CONNECTED){
      Serial.print("Attempting to connect");
      while(WiFi.status() != WL_CONNECTED){
        WiFi.begin(ssid, password); 
        delay(5000);     
      } 
      Serial.println("\nConnected.");
    }

    // Get a new temperature reading
    temp = dht.getTemperature();
    humid = dht.getHumidity();
    heat_index = dht.computeHeatIndex(temp, humid, false);
    dew_point = dht.computeDewPoint(temp, humid, false);

    if (isnan(humid) || isnan(temp)) {
      Serial.println(F("Failed to read from DHT sensor!"));
      return;
    }
    
    Serial.print("Temperature (ºC): ");
    Serial.println(temp);
    Serial.print("Humidity (%): ");
    Serial.println(humid);
    Serial.print(F("°Heat index (ºC): "));
    Serial.println(heat_index);
    Serial.print(F("°Dew Point (ºC): "));
    Serial.println(dew_point);

    
    ThingSpeak.setField(1, temp);
    ThingSpeak.setField(2, humid);
    ThingSpeak.setField(3, heat_index);
    ThingSpeak.setField(4, dew_point);
    int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);


    if(x == 200){
      Serial.println("Channel update successful.");
    }
    else{
      Serial.println("Problem updating channel. HTTP error code " + String(x));
    }
    lastTime = millis();
  }
}