はじめてのMKR ZERO (3) 温湿度DHT11

 温湿度センサDHT11の出力は40ビットのパルス列です。I2Cなどのデータ形式で出力できるAM2322もあります。Groveの4ピン・コネクタが付いた製品を入手しました。4ピンですが、I2C信号ではありません。

DHTのライブラリを導入

 最初、ライブラリマネージャでDHTで検索して出てきたGrove Temperature And Humidity Sensor by Seeed Studioを入れて実行しました。コンパイルはできたのですが、実行結果の表示が0%、0℃でした。
 AdafruitのDHT sensor library をインストールします。

 このライブラリの動作には、Adafruit Unified Sensorが必要なので、同時にインストールします。

接続

 Groveのセンサには、信号とVccの間に10kΩの抵抗がつながっています。DHT11の動作電圧は3.3~5Vです。

MKRZERO DHT
GND GND
Vcc(3.3V) Vcc
 - NC
2 SIG

サンプル・スケッチの実行

 DHT sensor library のDHTtesterを読み込み、センサの種類の記述部分、

#define DHTTYPE DHT11

だけを有効にしますDHT11の出力は2ピンにつないだので、

#define DHTPIN 2

とし、コンパイルして書き込みます。実行中の様子です。

LCDに結果を表示

 前回の16×2キャラクタ表示LCDに、温度と湿度の測定結果を表示します。

// Written by ladyada, public domain
#include <Wire.h>
#include "rgb_lcd.h"
#include "DHT.h"

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

DHT dht(DHTPIN, DHTTYPE);
rgb_lcd lcd;
const int colorR = 200;
const int colorG = 200;
const int colorB = 200;

void setup() {
Serial.begin(9600);
Serial.println("DHT11 start");
lcd.begin(16, 2);
lcd.setRGB(colorR, colorG, colorB);
dht.begin();
}

void loop() {
delay(2000);
lcd.setCursor(0, 0);
// 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"));

lcd.setCursor(0, 0);lcd.print("Temperature:");lcd.print(t,1);
lcd.setCursor(0, 1);lcd.print("Humidity:");lcd.print(h,0);
}

前へ

はじめてのMKR ZERO (2) キャラクタ表示LCD

次へ

はじめてのMKR ZERO (4) SDメモリ