개발자/Arduino

아두이노 DHT11 온도 습도 센서 실습

지구빵집 2022. 4. 11. 20:00
반응형

 

 

온도 습도 센서 연결도는 아래와 같습니다.

 

 

아두이노 DHT11 온도 습도 센서 실습

 

 

Arduino 프로그래밍

 

Arduino IDE 소프트웨어가 실행되고 있어야 합니다 . 다음으로 Arduino 라이브러리 관리자를 통해 수행할 수 있는 DHT 센서 라이브러리를 설치해야 합니다. 스케치 화면에서 툴 → 라이브러리  관리자 → 라이브러리 관리 창을 열어서 검색 필드에 " dht zsensor"를 입력 하고 " Adafruit 의 DHT 센서 라이브러리 " 목록을 살펴봅니다 .

 

"설치" 버튼을 클릭하거나 이전 버전에서 "업데이트"를 클릭합니다. 

 

Arduino 라이브러리 관리자

 

소스코드

 

#include "DHT.h"

#define DHTPIN 2     // Digital pin connected to the DHT sensor

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println(F("DHTxx test!"));

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its 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);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // 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);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

 

위 소스코드의 결과는 아래와 같습니다.

 

씨리얼 모니터 출력 화면

 

 

씨리얼 플로터 기능을 사용하기 위해 코드를 단순하게 만들었어요. 아래 코드를 카피하고 붙여넣으세요.

 

#include "DHT.h"
#define DHTPIN 2     // Digital pin connected to the DHT sensor

#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("temp, Humi");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  
  int temp = (int)dht.readTemperature();
  int humi = (int)dht.readHumidity();

  
  Serial.print(temp); //온도값 시리얼 모니터에 출력
  Serial.print(',');
  Serial.println(humi); //습도: 출력
  
 
}

 

위 코드로 씨리얼 모니터와 씨리얼 플로터로 출력한 결과입니다. 손으로 만지거나 입김을 불면 온도가 변화하는 것을 확인하실 수 있습니다.

 

씨리얼 모니터 출력 결과

 

씨리얼 플로터 출력 결과

 

참고

How to use dht11 with arduino

아두이노로 그래프 그리기

 

 

반응형