ESP8266 + DHT11 温湿度监控

Scroll Down

最近买了个 ESP8266 + DHT11 来做

设备:

  1. NodeMCU开发板一块
  2. DHT11温湿度传感器一个

参考文章资料
https://blog.bbskali.cn/1337.html

image.png

/*
    This sketch demonstrates how to scan WiFi networks.
    The API is almost the same as with th
e WiFi Shield library,
    the most obvious difference being the different file you need to include:
*/
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <dht11.h>
dht11 DHT11;


#ifndef STASSID
#define STASSID "Xiaomi_C0AC"
#define STAPSK  "12345678"
#endif
// 温度读取PIN口
#define DHT11PIN 2

const char* ssid = STASSID;
const char* password = STAPSK;

// 连接上好像是6
int wifiStatus = WL_IDLE_STATUS;

// ip 地址
String ipAddress = "";

void setup() {
  Serial.begin(115200);
  // wifi 连接函数, 会自动判断连接状态, 开机时候连接 wifi 即可, 暂时不判断断开状态情况
  wifi_connect();
}

void loop() {
  // 扫描 WiFi
  // scanner_wifi();
  // get_wifi_status();
  get_dht11();
  delay(5000);
}



/**
 * wifi连接函数
 */
void wifi_connect() {
  // 如果wifi 没连接
  if (wifiStatus == WL_IDLE_STATUS) {
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);
    wifiStatus = WiFi.begin(ssid, password);
    delay(10000);
    cc_print("当前 wifi 状态: ", wifiStatus);
    Serial.println("wifi 连接完毕!");
  }
}

/**
 * 获取dht11 温湿度信息
 */
void get_dht11() {
  DHT11.read(DHT11PIN);
  Serial.print("当前湿度 (%): ");
  Serial.println((float)DHT11.humidity, 2);
  Serial.print("当前温度 (oC): ");
  Serial.println((float)DHT11.temperature, 2);
  // DHT11 最大每秒读取一次 DHT22 每两秒读取一次

}

void get_wifi_status() {
  if (ipAddress == "") {
    String ip_address_temp = WiFi.localIP().toString();
    if (ip_address_temp != "(IP unset)") {
      ipAddress = WiFi.localIP().toString();
    }
    cc_print("wifi status: ", wifiStatus);
    cc_print("module IP address: ", WiFi.localIP().toString());
    cc_print("gateway IP address: ", WiFi.gatewayIP().toString());
  }
}

/**
 * wifi 扫描函数
 */
void scanner_wifi() {
  Serial.println("开始扫描wifi");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("扫描完毕");
  if (n == 0) {
    Serial.println("没有可用的WiFi!");
  } else {
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}


void cc_print(String cc_prefix,String cc_suffix) {
   Serial.print(cc_prefix);
   Serial.println(cc_suffix);
}


void cc_print(String cc_prefix,int cc_suffix) {
   Serial.print(cc_prefix);
   Serial.println(cc_suffix);
}