---
title: "Visualize office temperature and humidity with Arduino and Datadog"
url: "https://maker.wiznet.io/WIZnet/projects/visualize-office-temperature-and-humidity-with-arduino-and-datadog/"
markdown_url: "https://maker.wiznet.io/WIZnet/projects/visualize-office-temperature-and-humidity-with-arduino-and-datadog/md"
type: "UCC: User Created Content"
author: "Daiki Matsui"
author_url: "https://tech.plaid.co.jp/aruduino-datadog"
editor: "WIZnet"
editor_url: "https://maker.wiznet.io/"
original_author: "Daiki Matsui"
original_url: "https://tech.plaid.co.jp/aruduino-datadog"
published: "2023-02-06"
language: "en"
hardware: ["Arduino Ethernet Shield 2"]
likes: 3
views: 291
comments: 0
source: "WIZnet Makers (https://maker.wiznet.io/)"
---

# Visualize office temperature and humidity with Arduino and Datadog

> This time, I will use Arduino, which was sleeping at my home, and Datadog, which is used to monitor the infrastructure, to visualize

Original author: Daiki Matsui (source: https://tech.plaid.co.jp/aruduino-datadog)

## Components

- **Arduino Ethernet Shield 2** x 1 ([docs](https://docs.arduino.cc/hardware/ethernet-shield-rev2))

## Article

こんにちは、プレイドの @ikemonn です。

プレイドでは[KARTE](https://karte.io/)というサービスを提供しており、私は主にインフラ側を担当しております。

今回は私の自宅で眠っていた[Arduino](https://www.arduino.cc/)とインフラの監視で利用している[Datadog](https://www.datadoghq.com/)を使用してオフィスの温度・湿度を可視化しようと思います。

## **概要**

[Datadog](https://www.datadoghq.com/)とは、システムモニタリングツールで、Karteではサーバの監視やAPIのレスポンタイムの可視化、AWSの利用金額のモニタリング等に利用しています。
AWSやSlack、PagerDutyなど様々なサービスとの連携もしやすく重宝しています。

今回は下記のような手順で温度・湿度をArduinoで計測しDatadogにデータを投げてグラフとして表示させます。

Arduino UnoだとEthernet Shield2を使用しても、[https通信は厳しいようなので](http://arduino.stackexchange.com/questions/4/how-to-get-https-on-arduino)一旦Nodeサーバにhttp通信でデータを送ってNodeサーバからDatadogのAPIを叩きにいきます。

1. Arduinoで温度・湿度を計測する

2. ArduinoからMac上で動かしているNode.jsのサーバに温度・湿度を送信する

3. Node.jsサーバが温度・湿度を受け取ったらDatadogにデータを送る

また毎時&異常値が出た時にSlackに通知するように設定します。

- Mac上のcronで毎時、温度・湿度をSlackに通知

- Datadogのモニタリングでしきい値に達したらSlackにアラートを投げる

![スクリーンショット 2016-02-14 19.28.03.png (133.3 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/bbeab84e-7064-459c-a543-ed8bd3e6e36a/00aff04d-4057-403b-b0d4-fd6d4e627247.png)

## **使用したもの**

- [Arduino Uno](http://www.amazon.co.jp/%E3%82%B9%E3%82%A4%E3%83%83%E3%83%81%E3%82%B5%E3%82%A4%E3%82%A8%E3%83%B3%E3%82%B9-%E3%80%90%E6%B0%B8%E4%B9%85%E4%BF%9D%E8%A8%BC%E4%BB%98%E3%81%8D%E3%80%91Arduino-Uno/dp/B0044X2E5S/ref=sr_1_1?ie=UTF8&qid=1455603981&sr=8-1&keywords=arduino+uno)

- [温湿度センサ モジュール AM2302](http://akizukidenshi.com/catalog/g/gM-07002/)

- [Arduino Ethernet Shield 2](http://www.arduino.org/products/shields/5-arduino-shields/arduino-ethernet-shield-2)

- LANケーブル

- 10KΩ抵抗

![Slack for iOS Upload (1).jpg (539.0 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/8dd3bac1-d77c-44b9-8f2b-287cf709ad5f/cd32e7e5-4f9e-45e5-9e54-76efe54d76ef.jpg)

## **手順**

### **Ethernet Shield2を取り付ける**

Arduino Unoはデフォルトでは通信ができないので、Ethernet Shield2を使ってhttp通信が出来るようにします。
後ほど使うので、Ethernet Shield2に貼られているmacアドレスをメモしておいてください。
下記の画像のようにArduinoのピンに合わせてEthernet Shield2をとりつけます。

![Slack for iOS Upload (2).jpg (467.0 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/deaa470b-2bfd-4969-9ee2-47f0715f3d71/ed2198d8-3295-4b54-89b2-e758a012b937.jpg)

### **配線する**

今回は下記の画像のように配線しました。

![2016_0215_engineerblog_ブレッドボード.png (155.3 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/cd01eda0-1065-4a05-90c1-7dd5b0f5eade/99c0a6af-5064-44b4-a84b-ec7da8c82457.png)

### **コードを書く**

今回はEthernet Shield 2を使用するので、[Arduino IDE v1.7.2以降](http://www.arduino.org/software)をDLします。

![スクリーンショット_2016-02-15_22_46_22.png (348.2 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/05e78657-e6ae-4a89-8702-07f8a0160245/02e83495-bdf0-48fb-9142-4ff95843816f.png)

#### **湿度・温度の取得**

温湿度センサAM2302用のライブラリもあるので、[adafruit/DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library)からgit cloneしておきます。

Arduino IDEを起動し、[メニューバー] -> [スケッチ] -> [ライブラリを使用]-> [ライブラリをインストール]から先ほどcloneしたフォルダを選択します。

![スクリーンショット_2016-02-15_23_04_11.png (687.0 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/48cf2cba-94ef-41e4-98bd-f63490ba1955/ff1b8433-1897-439a-904a-3c74b4bec9b8.png)

[ArduinoとAM2302を使って温湿度センサを作る – QuZeeBlog@Hatena](http://quzee.hatenablog.com/entry/2015/03/19/235400)を参考にコードを書いていきます。

```plaintext
#include "DHT.h"
#define DHTTYPE DHT22
#define DHT22_PIN 7
DHT dht(DHT22_PIN, DHTTYPE);

void setup() {
  pinMode(DHT22_PIN, INPUT);
  Serial.begin(9600);
}

void loop()
{
  // 湿度と温度(摂氏)を取得する
  float h  = dht.readHumidity() ;
  float t  = dht.readTemperature();
  Serial.print("humid: ");
  Serial.print(h);
  Serial.print("temp: ");
  Serial.println(t);

  delay(2000);

}
```

これをコンパイルして実行すると下記のように湿度と温度が取れます。
体感は25℃もない気がするのですが、センサによると気温25度らしいです。

![スクリーンショット 2016-02-16 11.39.55.png (164.9 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/13aae03c-3086-4829-8641-dcd612afb0c9/e8f47c18-2411-46d5-9b08-acd210660cd6.png)

#### **EthernetでMacに通信する**

続いて、Ethernet経由でMac内に立てたNode.jsサーバにアクセスしてみます。
[メニューバー] -> [ファイル] -> [スケッチの例] -> [Ethernet2] -> [WebClient]をもとにコードを書きます。

![スクリーンショット 2016-02-16 11.44.08.png (4.1 MB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/6c1796a6-6b68-4081-afca-8185ba7a280f/8ca32f32-026a-4c93-84f3-125bdf763c9e.png)

下記の部分を書き換えます

- byte macにEthernet Sieldのmacアドレス

- IPAddress ipにArduinoに割り振るIPアドレス

- char serverにMacのローカルIP

- client.connect(server, [ポート])にNodeサーバのポート番号(3000番で立ち上げます)

```plaintext
#include <SPI.h>
#include <Ethernet2.h>
// 先ほどメモしたEthernet SieldのMacアドレス
byte mac[] = { 0x90,0xA2,0xDA,0x10,0x67,0xBA }; 
// MacのローカルIP(ifconfigコマンドで調べられる)
char server[] = "192.168.1.66"; 
 // Arudinoに割り当てるIPアドレス(使われていなさそうなIPを適当に設定する)
IPAddress ip(192, 168, 1, 2);

EthernetClient client;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Ethernet.begin(mac, ip);
  }

  delay(1000);
  Serial.println("connecting...");

  // Nodeサーバでlistenしているポートを第二引数に指定(今回は3000番)
  if (client.connect(server, 3000)) { 
    Serial.println("connected");
    // q=arduinoが送信される
    client.println("GET /?q=arduino HTTP/1.1");
    client.println("Host: 192.168.1.66");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    while (true);
  }
}
```

Node.js

```plaintext
var express = require('express');
var app = express();

app.get('/', function (req, res) {
    console.log(req.query);
});

app.listen(3000, function () {
  console.log(‘App listening on port 3000!');
});
```

Nodeサーバを立ち上げた後に、ArduinoIDEからコードをコンパイルして実行すると下記のようにパラメータが送られてきているのがわかります。

![スクリーンショット 2016-02-16 12.25.43.png (10.3 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/b8df7c57-0d16-4925-8752-4cb01617f287/3b72ca2b-3b51-4386-ab7c-0b3a3f236fcf.png)

#### **Nodeサーバに湿度と温度をおくる**

ここまででArduinoで温度・湿度を取得する & ArduinoからNodeサーバにデータが送信できるようになりました。
次にそれらを組み合わせてNodeサーバに温度と湿度を送ってみます。

```plaintext
#include <DHT.h>
#include <SPI.h>
#include <Ethernet2.h>

#define DHTTYPE DHT22
#define DHT22_PIN 7
DHT dht(DHT22_PIN, DHTTYPE);
// Ethernetシールドのmacアドレス
byte mac[] = { 0x90,0xA2,0xDA,0x10,0x67,0xBA };
// MacのローカルIP
char server[] = "192.168.1.66";
// 自身のネットワークによって変更する
IPAddress ip(192, 168, 1, 2);
EthernetClient client;

unsigned long lastConnectionTime = 0;
// 60秒ごとに送信する
const unsigned long postingInterval = 60L * 1000L;

void setup() {
  pinMode(DHT22_PIN, INPUT);
  Serial.begin(9600);

  delay(1000);
  Ethernet.begin(mac, ip);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  if (millis() - lastConnectionTime > postingInterval) {
    float h  = dht.readHumidity() ;
    float t  = dht.readTemperature();
    httpRequest(h, t);
  }
}

void httpRequest(float humid, float temp) {

  client.stop();

  if (client.connect(server, 3000)) {
    Serial.println("connecting...");
    Serial.println("humid is ");
    Serial.println(humid);
    Serial.println("temp is ");
    Serial.println(temp);
    // /?h=25.02&t=38.23という形式で送る
    client.print("GET ");
    client.print("/?h=");
    client.print(humid);
    client.print("&t=");
    client.print(temp);
    client.println(" HTTP/1.1");
    client.println("Host: 192.168.1.66");
    client.println("Connection: close");
    client.println();

    lastConnectionTime = millis();
  }
  else {
    Serial.println("connection failed");
  }
}
```

このようにデータが送信されます。

![スクリーンショット 2016-02-16 12.40.18.png (105.8 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/99b1787d-cbba-479e-917e-9e5e8f7ca391/5246e73a-b0fc-4789-ab40-f9fce1fb105e.png)

#### **Datadogにデータを送ってみる**

では最後に[Datadog](https://www.datadoghq.com/)に湿度と温度を送ってグラフ化してみましょう。
[Datadog](https://www.datadoghq.com/)にアカウント登録して、Mac用のDatadog Agentをインストールします。

データの送信の際に[node-datadog](https://github.com/HashGo/node-datadog)を使用するので、Node.jsサーバと同じディレクトリにgit cloneしておきます。
下記のapi_keyとapp_keyはご自身のアカウントの情報を埋めてください。

```plaintext
var express = require('express');
var app = express();

var DataDog = require('./node-datadog');
var api_key = "your api key";
var app_key = "your app key";
var dd = new DataDog(api_key, app_key);

app.get('/', function (req, res) {
    console.log(req.query);
    var temp = req.query['t'];
    var humid = req.query['h'];

    dd.postSeries({
        "series": [
            {
                "metric": "arduino.temperature",
                "points": [
                    [Date.now()/1000, req.query['t']]
                ],
                "type": "gauge",
                "tags": ["arduino", "temperature"]
            },
            {
                "metric": "arduino.humidity",
                "points": [
                    [Date.now()/1000, req.query['h']]
                ],
                "type": "gauge",
                "tags": ["arduino", "humidity"]
            }
        ]
    });

});

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});
```

Datadogにアクセス後、左列の[Metrics] -> [Explore]から先ほど送信したデータを確認できます。

下記のように温度と湿度が送信されていればOKです。

![スクリーンショット 2016-02-16 13.15.34.png (118.8 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/2abfda00-0955-4efc-89c4-44cd42542c32/b80712f0-008d-4763-83f3-41e316ef855b.png)

DatadogにはDashboardという機能があり、特定のグラフや数値をまとめて見やすくすることができます。
KarteではサーバごとのCPU使用率やメモリ使用量、レスポンスタイム等を表示しています。

![スクリーンショット 2016-02-16 13.11.43.png (110.0 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/ecffba69-ec38-49da-88d7-1f5f799b09e8/efe36290-128b-430d-9bc2-57adbbe7aada.png)

#### **毎時温度と湿度をSlackにポストする**

Datadogに送られているデータを取得して、毎時Slackに温度と湿度をポストします。
下記のshellを保存し、Macのcrontabから毎時実行するように設定します。
事前にSlackの”Incoming Webhook”を設定し、WebhookのURLを取得しておいてください。
また、jqコマンドを使用するので、`brew install jq`等でjqをインストールしておいてください。

![スクリーンショット 2016-02-16 12.57.59.png (85.0 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/0ce82a78-85c9-4935-91ec-04d207e97539/a7c1d43f-3629-47b5-b5db-97e393ee1a86.png)

```plaintext
#!/bin/sh

get_temp() {
    local DD_API_KEY=$1
    local DD_APP_KEY=$2
    local FROM_TIME=$3
    local TO_TIME=$4

    temp=$(curl -sG 
        "https://app.datadoghq.com/api/v1/query" 
        -d "api_key=${DD_API_KEY}" 
        -d "application_key=${DD_APP_KEY}" 
        -d "from=${FROM_TIME}" 
        -d "to=${TO_TIME}" 
        -d "query=arduino.temperature{*}by{host}" 
        | /usr/local/bin/jq '.series[].pointlist[-1][1]' 
        | xargs printf "%.2f")

    echo $temp
}

get_humid() {
    local DD_API_KEY=$1
    local DD_APP_KEY=$2
    local FROM_TIME=$3
    local TO_TIME=$4

    humid=$(curl -sG 
        "https://app.datadoghq.com/api/v1/query" 
        -d "api_key=${DD_API_KEY}" 
        -d "application_key=${DD_APP_KEY}" 
        -d "from=${FROM_TIME}" 
        -d "to=${TO_TIME}" 
        -d "query=arduino.humidity{*}by{host}" 
         | /usr/local/bin/jq '.series[].pointlist[-1][1]' 
         | xargs printf "%.2f")
    echo $humid
}


notify_to_slack() {
  local TEMP=${1:-"null"}
  local HUMID=${2:-"null"}
  local COLOR=${3:-"#439FE0"}
  local CHANNEL="#test_ikemonn"
  local USER_NAME="arduino"
  local MSG="現在の温度は${TEMP}度、湿度は${HUMID}%です。"
  local WEBHOOK="your webhook"

  post_data=`cat <<-EOF
  payload={
    "channel": "${CHANNEL}",
    "username": "${USER_NAME}",
    "attachments": [
      {
        "fallback": "Fallback $MSG",
        "color": "${COLOR}",
        "title": "${MSG}"
      }
    ]
  }
EOF`

  curl -X POST $WEBHOOK --data-urlencode "${post_data}"
}

main() {
    local DD_API_KEY="your api key"
    local DD_APP_KEY="your app key"
    local TO_TIME=$(date +%s)
    local FROM_TIME=$(date -v -1H +%s)

    local temp=$(get_temp ${DD_API_KEY} ${DD_APP_KEY} ${FROM_TIME} ${TO_TIME})
    local humid=$(get_humid ${DD_API_KEY} ${DD_APP_KEY} ${FROM_TIME} ${TO_TIME})

    notify_to_slack $temp $humid
}

main
```

上記ファイルを保存した後、crontabの設定をします。

```plaintext
# Macにcronを設定する
$ crontab -e
# 平日10~19時の毎時0分に温度・湿度をSlackに通知
0 10-19 * * 2-6 /your/path/to/arduino_post_to_slack.sh
```

![スクリーンショット 2016-02-16 15.44.54.png (29.7 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/c49110b6-01ef-4d15-b296-019e12966313/d1add31b-93b2-433f-a543-e70c4f5e4450.png)

### **アラートを設定する**

最後に温度・湿度がしきい値を超えている時にアラートをSlackに通知するように設定します。
Datadogの”Monitor”という機能を使ってアラートを設定します。
例えば湿度が40%以下の状態が1分以上続いた時に通知したいなどといった設定ができます。

![スクリーンショット 2016-02-16 15.13.45.png (145.9 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/81548553-bacf-4b99-a0e5-e4b24687caf8/011382bb-d973-4052-858f-943790d3c6c0.png)

Datadogでは、特定の値だけではなく変化量(値が1分で50%以上増加等)でもアラートを設定できるので便利です。
また、Slackに通知される時にグラフも見られるので状況が分かりやすくて助かります。

![スクリーンショット 2016-02-16 15.47.01.png (43.7 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/8b0635d8-06a9-4035-9aee-94ea38818de0/d00a9045-5a3a-475c-9baa-3c2b21ab48a8.png)

## **最後に**

Lチカを試しただけでお蔵入りになっていたArduinoを活用できて良かったです。
1日ほどで作成できますので、家で眠っているArduinoがある方は試してみてはいかがでしょうか？
http通信ができると色々試せることが増えるのでEthernetSield2は買って良かったです。
一方、Arduino Unoだとhttps通信ができないので一旦Nodeサーバ等にデータを送ってから、各種APIを叩きにいかないといけないところが少し面倒でした。

他にも様々なセンサが売られているので今後も試してみようと思います！

PlaidではIoT関係ですと、他にも@makinoyが作った打刻システムが使われていたりします。(定期券等の磁気カードをかざすと打刻される)

![Slack for iOS Upload (3).jpg (483.6 kB)](https://ik.imagekit.io/newt/61b151f921640c0018173598/2f000e84-feb8-46e7-acb7-d358b0b7a4dd/f46b58a6-4610-45ee-8319-a3186f53aa08.jpg)

何でも自由に作れて皆に使ってもらえる風土がありますので、ご興味のある方は是非！

ウェブ接客プラットフォーム「[KARTE](https://karte.io/)」を運営するプレイドでは、
こうやって自由に作れる技術に興味を持つエンジニア（インターンも！）を募集しています。

詳しくは[こちら](https://www.wantedly.com/companies/plaid/projects)（Wantedly）をご覧ください。
もしくはこちらのボタンよりお気軽に「話を聞きに行きたい」と押してください！

## **参考**

- [ArduinoとAM2302を使って温湿度センサを作る – QuZeeBlog@Hatena](http://quzee.hatenablog.com/entry/2015/03/19/235400)

- [ethernet – How to get HTTPS on Arduino? – Arduino Stack Exchange](http://arduino.stackexchange.com/questions/4/how-to-get-https-on-arduino)

---

Source: https://maker.wiznet.io/WIZnet/projects/visualize-office-temperature-and-humidity-with-arduino-and-datadog/
