Use arduino IDE to develop ESP8266NodeMCU and connect DHT11 to realize temperature and humidity detection and upload to onenet official website

Foreword:

        This blog records the use of arduino IDE to develop ESP8266NodeMCU, realize the temperature and humidity detection with DHT11, and upload the new version of onenet official website; It's a bit uncomfortable. In the spirit of open source, this blog will make up for the lack of information in this area.

initial preparation work:

Hardware:

        1、ESP8266NodeMCU

         2. DHT11 sensor

         3. A USB to micoUSB cable, several Dupont cables

Create a device on the new version of Onenet

        1. First of all, we need to register a onenet account, and I will not write specific steps for you here.

        2. After registration, click the arrow to enter the developer center

         3. Continue to click on the cost center

         4. A brand new interface will pop up

        5. Hover the mouse over the area pointed by the arrow on the left, and the following interface will be expanded 

        6. Select multi-protocol access

         7. We click to add products

         8. Write some necessary information according to the arrows and box prompts. This can be written casually, as long as we confirm that the networking method is wifi and the access protocol is MQTT (old version).

         9. We click to add the device immediately

        10. Click Add Device

         11. A new interface will pop up for us

         12. You can also write casually here. After writing the required options, click Add.

         13. After the addition is completed, we can see a new interface. In this interface, the device is offline at the beginning, which is normal. In addition, our device ID needs to be recorded, and we need to follow up according to the device ID. Modify your own code.

         14. We click on this detail to see our overall equipment situation

        15. After entering the new interface, we click Add APIkey

         16. This APIKey can be set by ourselves. I will write it casually here. This official website will generate a corresponding APIKey code for us. I just write it casually here, as long as there are enough 16.

         17. After clicking Submit, a new APIKey will be generated for us. This should also be remembered, and subsequent code writing should also be remembered.

         19. Let's click on the product overview to check our product ID, and record this, because we will also use it for subsequent code writing.

         So far, our onenet device is configured, and the next step is to add an ESP8266 device on the arduino IDE.

arduinoIDE add ESP8266

        If we choose to use arduino IDE to edit ESP8266 at the beginning, we need to do some operations on the editor

        1. Open File -> Preferences in the menu bar, and copy the URL below to the specified location

http://arduino.esp8266.com/stable/package_esp8266com_index.json

      

         2. Then open the tool, hover the mouse over the position of the development board, and the development board management will appear. If it does not appear, it just means that the Arduino version is different. There is no problem with this, as shown in the figure

         3. We click on the development board management, and the following interface pops up. We search for ESP8266 in the area pointed by the arrow, and then find a suitable version to download.

         4. Start downloading.

         5. This process is very error-prone, and it doesn’t matter if you make a mistake. Once an error is reported, download it several times. Make sure the network is smooth, otherwise the download will fail.

        6. After the download is complete, we need to restart our IDE to find our downloaded development board in the location of the development board. Here we must choose the development board that I hover over with the mouse. The development board corresponding to our ESP8266NodeMCU is NodeMCU 1.0 , you must not choose the wrong one here, otherwise it is easy to make some mistakes.

 Install the driver of CP2102

       If we connect the ESP8266NodeMCU to our computer at the beginning, there is no way to recognize our serial port, that is to say, the burning code cannot be burned in at the beginning. If you plug in the ESP8266NodeMCU, the following interface will appear in the device manager of the computer.

        Here I have installed the CP2102 driver before. At first I misread it and thought that the ESP8266NodeMCU onboard is the CH340 driver. After a closer look, it is not. We also need to install a CP2102 driver. Here I also found it for you. A suitable driver, I put it in the Baidu network disk, the CP2102 driver    extraction code is: brqt

        After downloading, we choose the corresponding driver according to the type of computer. For 64-bit, we choose X64, and for 32-bit, we choose X86.

         Double-click to run. Just click Next, fool-proof installation.

         After the installation, we can find that the serial port is recognized.

       So far, our preparatory work has been completed.

Hardware Pin Connections

        

DHT11 pin ESP8266NODEMCU pins
GND GND
VCC 3V3
DATA D6

code part:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Ticker.h>
#include <dht11.h>

#define WIFI_DEBUG 0          //1:使用一键配网,其它值则使用默认无线账号密码
#define DHT11PIN 12           //设置DHT引脚为Pin 12
#define ONENET_DISCONNECTED 1 //已经断开
#define ONENET_CONNECTED 2    //已经连接上
#define ONENET_RECONNECT 3    //重连成功
#define VER  "ESP8266_MQTT_V1.0"  //版本号

const char* ssid = "********";//你的wifi账号
const char* password = "********";//wifi密码


/*OneNet*/
PubSubClient mqttClient;
const char* mqttServer = "183.230.40.39";//mqtt服务器
const uint16_t mqttPort = 6002;       //端口号
#define onenet_productId   "******" //产品ID
#define onenet_deviceId    "**********" //设备ID
#define onenet_apiKey      "******************" //API_KEY

int state;
Ticker delayTimer;
WiFiClient espClient;
dht11 DHT11;

/* 延时N秒 */
void delayNs(uint8_t m){
  for(uint8_t index = 0;index<m;index ++){
    delay(1000);
    ESP.wdtFeed();
  }
}


/* 延时重启 */
void delayRestart(float t) {
  Serial.print("Restart after ");
  Serial.print(t);
  Serial.println("s");
  delayTimer.attach(t, []() {
    Serial.println("\r\nRestart now!");
    ESP.restart();
  });
}

/* 自动连接 */
bool autoConfig()
{
  WiFi.begin();
  for (int i = 0; i < 20; i++)
  {
    if (WiFi.status() == WL_CONNECTED)
    {
      Serial.println("AutoConfig Success");
      Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
      Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
      WiFi.printDiag(Serial);
      return true;
    }
    else
    {
      Serial.print("AutoConfig Waiting......");
      Serial.println(WiFi.status());
      delay(1000);
    }
  }
  Serial.println("AutoConfig Faild!" );
  return false;
}

/* 一键配网 */
void smartConfig()
{
  WiFi.mode(WIFI_STA);
  Serial.println("\r\nWait for Smartconfig");
  WiFi.beginSmartConfig();
  while (1)
  {
    Serial.print(".");
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    if (WiFi.smartConfigDone())
    {
      Serial.println("SmartConfig Success");
      Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
      Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
      WiFi.setAutoConnect(true);  // 设置自动连接
      break;
    }
    delay(1000); // 这个地方一定要加延时,否则极易崩溃重启
  }
}

/* 连接OneNet */
int connectToOneNetMqtt(){
    int cnt = 0;
    while(!mqttClient.connected()){
       ESP.wdtFeed();
       cnt++;
       Serial.println("Connect to OneNet MQTT...");
       
       if (mqttClient.connect(onenet_deviceId,onenet_productId,onenet_apiKey)) {
             Serial.println("connect success!");
             return ONENET_RECONNECT;
        } else {
             Serial.print("connect fail!");
             Serial.println(" try again in 5 seconds");
             delayNs(5);
        }
        if(cnt >=10){
          //只做10次连接到OneNet,连接不上重启8266
          cnt = 0;
          delayRestart(1);
        }
    }
    return ONENET_CONNECTED;
}

/* 云端下发 */
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  if ((char)payload[0] == '1') {
    digitalWrite(LED_BUILTIN, LOW);
  } else {
    digitalWrite(LED_BUILTIN, HIGH);
  }
}

/* 发布温度信息 */
void Temp_pubMQTTmsg(uint32_t data){
   long lastMsg = 0;

   char msg[50];
   char tmp[28];
   char d[3];
   snprintf(tmp,sizeof(tmp),"{\"Temp\":%d}",data);
   uint16_t streamLen= strlen(tmp);

   d[0]='\x03';
   d[1] = (streamLen >> 8);
   d[2] = (streamLen & 0xFF);
   snprintf(msg,sizeof(msg),"%c%c%c%s",d[0],d[1],d[2],tmp);
   mqttClient.publish("$dp", (uint8_t*)msg,streamLen+3,false);
}
/* 发布湿度信息 */
void Humi_pubMQTTmsg(uint32_t data){
   long lastMsg = 0;

   char msg[50];
   char tmp[28];
   char d[3];
   snprintf(tmp,sizeof(tmp),"{\"Humi\":%d}",data);
   uint16_t streamLen= strlen(tmp);

   d[0]='\x03';
   d[1] = (streamLen >> 8);
   d[2] = (streamLen & 0xFF);
   snprintf(msg,sizeof(msg),"%c%c%c%s",d[0],d[1],d[2],tmp);
   mqttClient.publish("$dp", (uint8_t*)msg,streamLen+3,false);
}

/* 初始化系统 */
void initSystem(){
    int cnt = 0;
    Serial.begin (115200);
    Serial.println("\r\n\r\nStart ESP8266 MQTT");
    Serial.print("Firmware Version:");
    Serial.println(VER);
    Serial.print("SDK Version:");
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println(ESP.getSdkVersion());
 
    ESP.wdtEnable(5000);
   
    if(WIFI_DEBUG==1)//开启一键配网模式
    {
       if (!autoConfig())
      {
        Serial.println("Start smartConfig");
        smartConfig();
      }
    }
    else
    {
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        cnt++;
        Serial.print(".");
        if(cnt>=40){
          cnt = 0;
          //重启系统
          delayRestart(1);
        }
        }
    }
    Serial.print("WIFI Connect \r\n");
}

/* 初始化ONENET通信 */
void initOneNetMqtt(){
    mqttClient.setServer(mqttServer,mqttPort);
    mqttClient.setClient(espClient);
    mqttClient.setCallback(callback);
}

/* 初始化 */
void setup() {
  initSystem();
  initOneNetMqtt();
}

/* 主函数 */
void loop() {
  ESP.wdtFeed();
  DHT11.read(DHT11PIN);
  state = connectToOneNetMqtt();
  Serial.println(WiFi.status());
  if(state == ONENET_RECONNECT){
     mqttClient.loop();
  }
  else if(state == ONENET_CONNECTED){
     printf("temp:%d \r\n",DHT11.temperature);
     printf("humi:%d \r\n",DHT11.humidity);
     Temp_pubMQTTmsg(DHT11.temperature);
     Humi_pubMQTTmsg(DHT11.humidity);
     mqttClient.loop();
  }
  delay(2000);
}

         What you need to modify here is the product ID, device ID, APIkey, and your own mobile phone hotspot and password that I reminded you to record.

        Of course, if you compile, you must first select the development board as ESP8266NodeMCU. then still report

        And these libraries can be found on the official website, and I will also sort out what to do if you don’t have these libraries.

What to do if there is no corresponding library

        1. Copy the URL below into your browser

https://www.arduino.cc/reference/en/libraries/

        2. Enter the following interface

         3. Search for the missing library where the arrow points to.

         4. Here I take PubSubClient.h as an example. After searching, click the first one

         5. Enter the following interface, here I choose the latest version, and it will be downloaded automatically after clicking.

         6. Enter the Arduino IDE, click Project -> Load Library -> Add .zip library. Select the file path just downloaded, specify the file, and install it directly. You can see the installation success prompt in the IDE command window.

         7. The same is true for the other libraries.

To compile:

        After compiling, it looks like this, not an error.

        Before burning, we need to select the serial port we just saw in the device manager, then click Tools -> Port -> select the serial port corresponding to CP2102, and then we can start burning.

        If the burning operation is performed, the effect shown in the figure below will appear, indicating that it is OK.

         At this time, the serial port viewing part is added to the code, and we can see the current temperature and humidity in the serial port monitor. We can open the serial monitor to see the effect.

         You can also enter the onenet official website to see the effect.

 

Guess you like

Origin blog.csdn.net/weixin_51651698/article/details/131262456