아두이노 코드 및 DHT22 온습도 센서용 비디오
이 튜토리얼에서는 Arduino와 함께 DHT22 온습도 센서를 사용하는 방법을 배우게 됩니다. AM2302로도 알려진 DHT22는 -40~80도 섭씨의 온도와 0~99%의 습도를 측정할 수 있습니다. 이 가이드를 따라 하면 섭씨, 화씨 또는 켈빈 단위의 온도와 습도 수준을 표시할 수 있습니다.

센서에서 데이터를 쉽게 읽기 위해 DHT 센서 라이브러리를 사용할 것입니다. 이 라이브러리는 DHT22와 통신하는 과정을 단순화하고 몇 줄의 코드만으로 온도와 습도 값에 접근할 수 있게 해줍니다. 더 자세한 설명을 원하시면 관련 비디오(비디오 00:00 부분)를 시청하시기 바랍니다.
하드웨어 설명
이 프로젝트의 주요 구성 요소는 디지털 온습도 센서인 DHT22 센서 모듈입니다. 이 센서는 정전식 습도 감지 요소와 서미스터를 사용하여 주변 공기를 측정합니다. 출력은 Arduino가 읽을 수 있는 디지털 신호입니다.
DHT22는 3.3~5볼트의 전압 범위에서 작동하며 단일 와이어 인터페이스를 통해 통신하므로 프로젝트에 쉽게 통합할 수 있습니다. 또한 최대 20미터의 긴 전송 거리를 지원하여 센서 배치에 유연성을 제공합니다.
데이터시트 세부 정보
| 제조업체 | Aosong |
|---|---|
| 부품 번호 | DHT22 (AM2302) |
| 로직/IO 전압 | 3.3 - 5 V |
| 공급 전압 | 3.3 - 5 V |
| 측정 범위 (온도) | -40 ~ +80 °C |
| 측정 범위 (습도) | 0 ~ 99 % |
| 정확도 (온도) | ±0.5 °C |
| 정확도 (습도) | 25 °C에서 ±2 % |
| 분해능 | 0.1 °C / 0.1 % |
| 전송 거리 | 최대 20 m |
| 패키지 | 4핀 모듈 |
- 3.3V~5V 사이의 적절한 전원 공급을 확인하세요.
- 데이터 핀과 전원 사이에 10K 풀업 저항을 사용하세요.
- 정확한 측정을 위해 센서 와이어를 짧게 유지하세요.
- 빠른 폴링을 피하고 측정 사이에 지연 시간을 두세요.
- 측정값에 영향을 줄 수 있는 환경 요인에 주의하세요.
배선 지침

DHT22 센서를 배선하려면 먼저 센서의 전원 핀(핀 1)을 Arduino의 5V 출력에 연결하세요. 다음으로 접지 핀(핀 4)을 Arduino의 GND 핀 중 하나에 연결합니다. 데이터 핀(핀 2)은 통신을 위해 Arduino의 디지털 핀 2에 연결해야 합니다. 또한 안정적인 측정을 위해 데이터 핀과 전원 핀 사이에 10K 저항을 배치하세요.
다른 핀을 데이터용으로 사용하는 경우 #define DHTPIN 값을 선택한 핀에 맞게 변경하여 코드를 업데이트해야 합니다. 설정은 간단하며 이러한 연결을 따르면 센서가 올바르게 작동합니다.
코드 예제 및 설명
다음 코드는 DHT22 센서를 초기화하고 온도와 습도 값을 읽습니다. 먼저 DHT 라이브러리를 포함하고 센서가 연결된 핀을 정의합니다:
#include "DHT.h"
#define DHTPIN 2 // 연결된 디지털 핀
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
여기서 DHTPIN 변수는 2로 설정되어 있으며, 이는 센서의 데이터 핀이 Arduino의 디지털 핀 2에 연결되었음을 나타냅니다. DHTTYPE은 사용된 센서 유형을 정의하며, 이 경우 DHT22입니다.
다음으로 setup() 함수에서 센서와 시리얼 모니터를 초기화합니다:
void setup() {
Serial.begin(9600);
dht.begin();
}
이 코드 조각은 시리얼 통신을 초기화하고 DHT 센서를 읽기 준비 상태로 만듭니다. Serial.begin(9600)은 시리얼 통신의 보드율을 설정합니다.
loop() 함수에서 온도와 습도 값을 읽고 표시할 수 있습니다:
Serial.print("Temperature: ");
Serial.print(getTemp("c")); // 섭씨
Serial.print(" *C ");
Serial.print(getTemp("h")); // 습도
Serial.println(" % ");
이 코드 부분은 섭씨 온도와 습도 백분율을 시리얼 모니터에 출력합니다. getTemp() 함수는 전달된 매개변수에 따라 요청된 데이터를 검색하는 데 사용됩니다.
시연 / 기대 효과
모든 것이 설정되고 코드가 업로드되면 시리얼 모니터에 온도와 습도 측정값이 표시됩니다. DHT22는 안정화되는 데 시간이 걸릴 수 있으므로 측정 사이에 몇 초의 간격을 두어야 합니다(비디오 15:00 부분). 측정값에 문제가 있는 경우 배선을 확인하고 연결이 안전한지 확인하세요. 일반적인 문제로는 잘못된 핀 할당이나 전원 공급 문제가 있습니다.
비디오 타임스탬프
- 00:00 - DHT22 센서 소개
- 01:30 - 센서 배선
- 03:00 - 코드 설명
- 04:30 - 코드 시연
- 06:00 - 결론
++
/*
* This is the Arduino code for the DHT22 module to read temperature and humidity.
* This code can display temperature in:
* getTemp("c") is used to get Celsius.
* getTemp("f") is used to get Fahrenheit.
* getTemp("k") is used for Kelvin.
* getTemp("hif") is used to get Fahrenheit.
* getTemp("hic") is used to get Celsius.
* getTemp("h") is used to get humidity.
* Watch the video https://youtu.be/oi_GPSLjgBY
* Other Arduino library and videos https://robojax.com
*
* Written/updated by Ahmad Shamshiri for Robojax.com Video
* Date: Jan 08, 2018, in Ajax, Ontario, Canada
* Permission granted to share this code given that this
* note is kept with the code.
* Disclaimer: This code is "AS IS" and for educational purposes only.
*
* original source code : https://github.com/adafruit/DHT-sensor-library
*/
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include "DHT.h"
#define DHTPIN 2 // what digital pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster processors.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx Robojax test!");
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Robojax.com test video
Serial.print("Temperature: ");
Serial.print(getTemp("c"));
Serial.print(" *C ");
Serial.print(getTemp("f"));
Serial.println (" *F");
Serial.println("-----------------");
Serial.print("Heat index: ");
Serial.print(getTemp("hic"));
Serial.print(" *C ");
Serial.print(getTemp("hif"));
Serial.println(" *F");
Serial.print(getTemp("k"));
Serial.println(" *K");
Serial.println("-----------------");
Serial.print("Humidity: ");
Serial.print(getTemp("h"));
Serial.println(" % ");
Serial.println("===========================");
}
/*
* getTemp(String req)
* returns the temperature related parameters
* req is string request
* This code can display temperature in:
* getTemp("c") is used to get Celsius.
* getTemp("f") is used to get Fahrenheit.
* getTemp("k") is used for Kelvin.
* getTemp("hif") is used to get Fahrenheit.
* getTemp("hic") is used to get Celsius.
* getTemp("h") is used to get humidity.
*/
float getTemp(String req)
{
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor).
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return 0.0;
}
// Compute heat index in Kelvin
float k = t + 273.15;
if(req =="c"){
return t;//return Celsius
}else if(req =="f"){
return f;// return Fahrenheit
}else if(req =="h"){
return h;// return humidity
}else if(req =="hif"){
return hif;// return heat index in Fahrenheit
}else if(req =="hic"){
return hic;// return heat index in Celsius
}else if(req =="k"){
return k;// return temperature in Kelvin
}else{
return 0.000;// if no request found, return 0.000
}
}
파일📁
아두이노 라이브러리 (zip)
-
DHT22 PCB module red
DHT22-module-red.fzpz0.01 MB
프리징 파일
-
DHT22 Humidity and Temperature Sensor
DHT22 Humidity and Temperature Sensor.fzpz0.01 MB -
DHT22 PCB module red
DHT22-module-red.fzpz0.01 MB
사용자 매뉴얼
-
DHT22 Temperature and Humidity sensor user's manual
robojax-DHT22_manual.pdf0.36 MB