Usage Note on WeMos D1

D1 WiFi UNO R3开发板基于ESP8266 ESP-12N F 模块,够自于淘宝。初步使用WeMos D1的代码如下(WeMosTest)。需要注意的地方包括:1)采用DHTesp或者DHT库应该都是可以的。2)连接A0口获取不到数据,连接D2口可以获取到相应的DHT11的数据。参考链接[1]。

/*  WeMos D1 Web Server, modified by Ma Can
 *  
 *  get weather info from internet, connect DHT11 to get home temptrature and humidity
*/
#include <DHTesp.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>  // http web access library
#include <ArduinoJson.h>        // JSON decoding library

#define DHTTYPE   DHT11         // define sensor type

const int DHTPIN = D2;
float h = 0;
float t = 0;

DHTesp dht;

const char* ssid     = "ap1";
const char* password = "ap1pass";

ESP8266WebServer server(80);
 
String webString="";     // String to display
// Generally, you should use "unsigned long" for variables that hold time
unsigned long previousMillis = 0;        // will store last temp was read
const long interval = 2000;              // interval at which to read sensor
 
void handle_root() {
  server.send(200, "text/plain", "Hello from WeMos Test Server, read from /feeder");
  delay(100);
}
 
void setup(void)
{
  // You can open the Arduino IDE Serial Monitor window to see what the code is doing
  Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable

  dht.setup(DHTPIN, DHTesp::DHT11);
  
  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.print("\n\r \n\rWorking to connect");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WeMos Test Server");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
   
  server.on("/", handle_root);
  
  server.on("/feeder", [](){
    webString = "Feeder Info:\n";
    getWeather("1");
    getLocalTempAndHum("2");
    server.send(200, "text/plain", webString);            // send to someones browser when asked
  });
  
  server.begin();
  Serial.println("HTTP server started");
}
 
void loop(void)
{
  server.handleClient();
}

void getLocalTempAndHum(String seq)
{  
  float t = dht.getTemperature();
  int h = dht.getHumidity();

  // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
  
  // print data
  Serial.printf("Temperature = %.2f°C\r\n", t);
  Serial.printf("Humidity    = %d %%\r\n", h);

  webString += seq;
  webString += ". Weather of Home:\n";
  webString += "\tTemperature = ";
  webString += t;
  webString += " C\n\tHumidity    = ";
  webString += h;
  webString += "\n";
}

void getWeather(String seq) 
{
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    http.begin("http://api.openweathermap.org/data/2.5/weather?q=BEIJING,cn&APPID=52acd267dd4d194c14d1e0b0d6a1e861");

    int httpCode = http.GET();

    if (httpCode > 0) {
      String payload = http.getString();
      
      DynamicJsonDocument doc(1024);

      // Parse JSON object
      DeserializationError err = deserializeJson(doc, payload);
      if (err) {
        Serial.print(F("deserializeJson() failed with code "));
        Serial.println(err.c_str());
        return; 
      }
 
      float temp = (float)(doc["main"]["temp"]) - 273.15;        // get temperature
      int   humidity = doc["main"]["humidity"];                  // get humidity
      float pressure = (float)(doc["main"]["pressure"]) / 1000;  // get pressure
      float wind_speed = doc["wind"]["speed"];                   // get wind speed
      int  wind_degree = doc["wind"]["deg"];                     // get wind degree
      const char *w = doc["weather"][0]["main"];
 
      // print data
      Serial.printf("Temperature = %.2f°C\r\n", temp);
      Serial.printf("Humidity    = %d %%\r\n", humidity);
      Serial.printf("Pressure    = %.3f bar\r\n", pressure);
      Serial.printf("Wind speed  = %.1f m/s\r\n", wind_speed);
      Serial.printf("Wind degree = %d°\r\n\r\n", wind_degree);
      
      webString += seq;
      webString += ". Weather of Beijing:\n";
      webString += "\tWeather = ";
      webString += w;
      webString += "\n\tTemperature = ";
      webString += temp;
      webString += " C\n\tHumidity    = ";
      webString += humidity;
      webString += " %\n\tPressure    = ";
      webString += pressure;
      webString += " bar\n\tWind speed  = ";
      webString += wind_speed;
      webString += " m/s\n\tWind degree = ";
      webString += wind_degree;
      webString += "\n";
    }
    http.end();
  }
}

Arduino IDE配置如下:

Leave a Reply

Your email address will not be published. Required fields are marked *