ESP8266とNode-REDで環境測定

多数のサイトの記事を参考にしたので、お礼の意味をこめてまとめてみる。

* ESP8266側

Wemos D1を使用（Aliexpressで300円程度）
センサはBME280（Aliexpressで300円程度）

![pic.jpg](https://qiita-image-store.s3.amazonaws.com/0/200022/784ba4cb-86e9-e1f3-3703-be4b3c9358aa.jpeg)

GPIO(D1）でBME280に電源供給する。
Wemos D1のD0とRSTを繋ぎDeepSleepさせる。
UDP接続でデータを送信する。

```ESP8266_BME280.ino
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

Adafruit_BME280 bme; // I2C
WiFiUDP port;

// 環境にあわせて設定
const char* ssid = "Wifi SSID";
const char* password = "Wifi Password";
const char* RemoteIP = "Node-RED PC IP Address";
const int RemoteUdpPort = "Port Number (Node-RED PC)";
const int LocalUdpPort = "Port Number (Wemos D1);

float h, t, p;
char tempStr[6];
char humidStr[6];
char presStr[7];

WiFiClient client;

void setup() {

  pinMode(D1, OUTPUT);
  digitalWrite(D1, HIGH);
  delay(500);
  Wire.begin(D3, D4);
  Wire.setClock(100000);
  // Connecting to WiFi network

  WiFi.begin(ssid, password);
  delay(500);
  port.begin(LocalUdpPort);
}

void loop() {

  digitalWrite(D1, HIGH);
  delay(500);
  bme.begin();
  delay(500);

  h = bme.readHumidity();
  t = bme.readTemperature();
  p = bme.readPressure() / 100.0F;

  dtostrf(t, 5, 1, tempStr);
  dtostrf(h, 5, 1, humidStr);
  dtostrf(p, 6, 1, presStr);
  delay(500);

  port.beginPacket(RemoteIP, RemoteUdpPort);
  port.write(tempStr);
  port.write(",");
  port.write(humidStr);
  port.write(",");
  port.write(presStr);
  port.endPacket();

  delay(500);
  client.stop();

  digitalWrite(D1, LOW);

  ESP.deepSleep(60 * 1000 * 1000);
  delay(1000);

}
```

* Node-RED側

![Node-red.png](https://qiita-image-store.s3.amazonaws.com/0/200022/407255ea-d43c-90dd-2746-ff5d5009cc93.png)

On/OffのスライドスイッチをOnにすると測定がはじまる。
測定中のデータはDownload dataのリンクからダウンロードできる。

node-red-dashboardをインストールしておく。

データファイルはC:\Users\ユーザー名\.node-red\public\data.txtに保存する。このため、setting.jsを一部書き換える。

```C:\Users\ユーザー名\.node-red\setting.js

// When httpAdminRoot is used to move the UI to a different root path, the
    // following property can be used to identify a directory of static content
    // that should be served at http://localhost:1880/.
    httpStatic: 'C:\\Users\\ユーザー名\\.node-red\\public\\',

```

グラフ表示をリセットするには、msg.payload = [];で空データを送ればよい。

全体のプログラムはこのようなもの。

![無題.png.jpg](https://qiita-image-store.s3.amazonaws.com/0/200022/aa90eeaa-8ac9-6733-febf-63ea83cd8755.jpeg)

```Node-RED.json
[{"id":"875e011d.8c9b1","type":"udp in","z":"c7bd4892.5ff33","name":"","iface":"","port":"9000","ipv":"udp4","multicast":"false","group":"","datatype":"utf8","x":89,"y":20,"wires":[["f1039d99.7a42d"]]},{"id":"80368a94.88c5c8","type":"file","z":"c7bd4892.5ff33","name":"","filename":"C:\\Users\\ユーザー名\\.node-red\\public\\data.txt","appendNewline":true,"createDir":true,"overwriteFile":"false","x":585,"y":124,"wires":[]},{"id":"6b7eefba.564318","type":"ui_chart","z":"c7bd4892.5ff33","name":"","group":"8bb76dfe.1b24e8","order":3,"width":"11","height":"4","label":"グラフ（温度）","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":594,"y":356,"wires":[[],[]]},{"id":"a2865f64.6d69f8","type":"ui_chart","z":"c7bd4892.5ff33","name":"","group":"8bb76dfe.1b24e8","order":4,"width":"11","height":"4","label":"グラフ（湿度）","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":599,"y":414,"wires":[[],[]]},{"id":"f87cbe7b.9915","type":"ui_chart","z":"c7bd4892.5ff33","name":"","group":"8bb76dfe.1b24e8","order":5,"width":"11","height":"4","label":"グラフ（気圧）","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":600,"y":477,"wires":[[],[]]},{"id":"a04b648d.63b7d8","type":"ui_template","z":"c7bd4892.5ff33","group":"8bb76dfe.1b24e8","name":"ダウンロードリンク","order":2,"width":0,"height":0,"format":"  <a href=\"\\data.txt\" download=\"data.txt\"> Download Data </a>","storeOutMessages":true,"fwdInMessages":false,"templateScope":"local","x":586,"y":533,"wires":[[]]},{"id":"ede8ec78.465c5","type":"function","z":"c7bd4892.5ff33","name":"温度","func":"    msg={\"payload\":msg.data.split(\",\")[0],\"_msgid\":msg._msgid}\n    return msg;","outputs":1,"noerr":0,"x":357,"y":317.5,"wires":[["6b7eefba.564318"]]},{"id":"99103733.337488","type":"ui_switch","z":"c7bd4892.5ff33","name":"","label":"On/Off","group":"8bb76dfe.1b24e8","order":1,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"","style":"","onvalue":"true","onvalueType":"bool","onicon":"","oncolor":"","offvalue":"false","offvalueType":"bool","officon":"","offcolor":"","x":143,"y":166,"wires":[["c54f1a54.cdf26"]]},{"id":"f1039d99.7a42d","type":"change","z":"c7bd4892.5ff33","name":"","rules":[{"t":"set","p":"data","pt":"msg","to":"payload","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":115,"y":87.5,"wires":[["99103733.337488"]]},{"id":"d7dfeaf8.9a68c","type":"function","z":"c7bd4892.5ff33","name":"湿度","func":"if (msg.payload === true){\n    msg={\"payload\":msg.data.split(\",\")[1],\"_msgid\":msg._msgid}\n    return msg;\n}\nelse {\n    msg.payload = [];\n    return msg;\n}","outputs":1,"noerr":0,"x":360,"y":365,"wires":[["a2865f64.6d69f8"]]},{"id":"9a713371.3670b","type":"function","z":"c7bd4892.5ff33","name":"圧力","func":"if (msg.payload === true){\n    msg={\"payload\":msg.data.split(\",\")[2],\"_msgid\":msg._msgid}\n    return msg;\n}\nelse {\n    msg.payload = [];\n    return msg;\n}","outputs":1,"noerr":0,"x":363,"y":406,"wires":[["f87cbe7b.9915"]]},{"id":"33df85cb.326322","type":"file","z":"c7bd4892.5ff33","name":"","filename":"C:\\Users\\dino\\.node-red\\public\\data.txt","appendNewline":true,"createDir":true,"overwriteFile":"true","x":585,"y":169.5,"wires":[]},{"id":"4890f48b.3ec35c","type":"function","z":"c7bd4892.5ff33","name":"Onで追記保存","func":"\n    //タイムスタンプの生成\n  \n    var getTimestamp = function (date) {\n        var yyyy = date.getFullYear();\n        var mm = ('0' + (date.getMonth() + 1)).slice(-2);\n        var dd = ('0' + date.getDate()).slice(-2);\n        var h = ('0' + date.getHours()).slice(-2);\n        var m = ('0' + date.getMinutes()).slice(-2);\n        var s = ('0' + date.getSeconds()).slice(-2);\n        var temp = msg.data.split(\",\")[0];\n        var humid = msg.data.split(\",\")[1];\n        var pres = msg.data.split(\",\")[2];\n        var ts = yyyy + '/' + mm + '/' + dd + ',' + h + ':' + m + ':' + s+ ',' + temp + ',' + humid + ','+ pres;\n        return ts;\n    };\n    \n\n        msg.payload = getTimestamp(new Date());\n    \n    return msg;\n\n","outputs":1,"noerr":0,"x":343,"y":124,"wires":[["80368a94.88c5c8"]]},{"id":"2869448f.21bb54","type":"function","z":"c7bd4892.5ff33","name":"Offで新規保存","func":"\n    //タイムスタンプの生成\nif (msg.payload === true){\n    msg.payload = \"date,time,temp,humid,pres\";\n    return msg;\n}\n\n","outputs":1,"noerr":0,"x":342,"y":169,"wires":[["33df85cb.326322"]]},{"id":"c54f1a54.cdf26","type":"switch","z":"c7bd4892.5ff33","name":"","property":"payload","propertyType":"msg","rules":[{"t":"neq","v":"","vt":"prev"},{"t":"true"}],"checkall":"true","repair":true,"outputs":2,"x":149,"y":250.5,"wires":[["59f90ab8.8953dc","2869448f.21bb54"],["ede8ec78.465c5","d7dfeaf8.9a68c","9a713371.3670b","4890f48b.3ec35c"]]},{"id":"59f90ab8.8953dc","type":"function","z":"c7bd4892.5ff33","name":"非表示","func":"if (msg.payload === true){\n    msg.payload = [];\n    return msg;\n}","outputs":1,"noerr":0,"x":360,"y":456,"wires":[["6b7eefba.564318","a2865f64.6d69f8","f87cbe7b.9915"]]},{"id":"8bb76dfe.1b24e8","type":"ui_group","z":"","name":"温度・湿度・気圧測定","tab":"76ac02e3.760fb4","disp":true,"width":"11","collapse":false},{"id":"76ac02e3.760fb4","type":"ui_tab","z":"c7bd4892.5ff33","name":"ホーム","icon":"dashboard"}]
```