Arduino-ESP8266 sensor to obtain temperature and humidity

development environment

OS: win10x64
Arduino: 1.8.19
Development board: ESP8266
temperature and humidity sensor: unknown, can't read

Physical map

The blue one is the temperature and humidity sensor.
insert image description here

The obtained results

Celsius: Read temp1 success 22.90
Fahrenheit: Read temp2 success 73.22
Air humidity: Read humi success 44.00
insert image description here

install library

Arduino Software: Tools => Manage Libraries
insert image description here
insert image description here

The DHT11 library is used, install it

upper code

Basically, the notes for temperature and humidity are written. It's still a very simple code, mainly because the corresponding API has to check the library.

// 导入dht库,用于传感器的库
#include <DHT.h>

// 定义一个dht对象,5是GPIO5,具体看开发板
DHT dht(5, DHT11);

void setup() {
  // put your setup code here, to run once:
  //开启串口监视器
  Serial.begin(9600);
  //初始化dht传感器
  dht.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  //延迟1.5s 打印
  delay(1500);
  // 获取摄氏温度
  float temp1 = dht.readTemperature();
  // 获取华氏温度
  float temp2 = dht.readTemperature(true);
  // 获取空气湿度
  float humi = dht.readHumidity();
  // 判断读取到的数据
  if(isnan(temp1)){
    //没有读取到摄氏温度
    Serial.println("failed to read temp1");
  }else {
    //读取到摄氏温度,打印
    Serial.print("Read temp1 success");
    Serial.println(temp1);
  }
  
   if(isnan(temp2)){
    //没有读取华氏温度
    Serial.println("failed to read temp2");
  }else {
    //读取华氏温度,打印
    Serial.print("Read temp2 success");
    Serial.println(temp2);
  }

   if(isnan(humi)){
    //没有读取空气湿度
    Serial.println("failed to read humi");
  }else {
    //读取空气湿度,打印
    Serial.print("Read humi success");
    Serial.println(humi);
  }
}

Summarize

The first small program of the Internet of Things, on the ESP8266 development board, the temperature and humidity are obtained through the sensor. I am very excited. Let me commemorate it. Keep up the good work and encourage each other!

Guess you like

Origin blog.csdn.net/qwe1314225/article/details/123960617