Skip to main content

dht11

7、温湿度检测示例 示例功能:使用DHT11传感器检测空气中的温度和湿度值,并用串口打印出来。在使用DHT11温湿度检测传感器之前,需要预安装DHT11库文件

硬件接线:使用3P连接线将蜂鸣器模块连接在扩展板的8号IO口中


#include <DHT11.h>
DHT11 dht11(8);

void setup() {
Serial.begin(9600);
}

void loop() {
int temperature = 0;
int humidity = 0;
int result = dht11.readTemperatureHumidity(temperature, humidity);
if (result == 0) {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\tHumidity: ");
Serial.print(humidity);
Serial.println(" %");
} else {
// Print error message based on the error code.
Serial.println(DHT11::getErrorString(result));
}
}


/**
* DHT11 Temperature Reader
* This sketch reads temperature data from the DHT11 sensor and prints the value to the serial port.
* It also handles potential error states that might occur during reading.
*
* Author: Dhruba Saha
* Version: 2.1.0
* License: MIT
*/

// Include the DHT11 library for interfacing with the sensor.
#include <DHT11.h>

// Create an instance of the DHT11 class.
// - For Arduino: Connect the sensor to Digital I/O Pin 2.
// - For ESP32: Connect the sensor to pin GPIO2 or P2.
// - For ESP8266: Connect the sensor to GPIO2 or D4.
DHT11 dht11(6);

void setup() {
// Initialize serial communication to allow debugging and data readout.
// Using a baud rate of 9600 bps.
Serial.begin(9600);

// Uncomment the line below to set a custom delay between sensor readings (in milliseconds).
// dht11.setDelay(500); // Set this to the desired delay. Default is 500ms.
}

void loop() {
// Attempt to read the temperature value from the DHT11 sensor.
int temperature = dht11.readTemperature();

// Check the result of the reading.
// If there's no error, print the temperature value.
// If there's an error, print the appropriate error message.
if (temperature != DHT11::ERROR_CHECKSUM && temperature != DHT11::ERROR_TIMEOUT) {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
} else {
// Print error message based on the error code.
Serial.println(DHT11::getErrorString(temperature));
}
}