このページの翻訳は最新ではありません。ここをクリックして、英語の最新版を参照してください。
Arduino クライアントを使用したチャネルへのパブリッシュ
この例では、温度と湿度を測定する DHT11 センサーと光強度を測定するアナログ光センサーに接続された、Arduino® MKR1000 ボードを使用する方法を説明します。測定された値は、ThingSpeak™ チャネルにパブリッシュされます。ThingSpeak に送信するセンサーの値が複数ある場合には、複数の値をチャネル フィードにパブリッシュするよう選択できます。また、センサーが 1 つだけの場合は、単一の値をチャネル フィールドにパブリッシュできます。
メモ
DHT ライブラリには、最新バージョンではなく、Version 1.2.3 が推奨されます。[スケッチ]、[ライブラリをインクルード]、[ライブラリを管理] を使用し、検索バーに DHT
を入力して、Arduino IDE の使用するバージョンを調整します。
新しいチャネルでデータの収集での説明に従ってチャネルを作成します。
WiFi101.h
ライブラリとDHT.h
ライブラリを Arduino IDE にダウンロードします。SPI.h
、WiFi101.h
、PubSubClient.h
、DHT.h
の各ライブラリを Arduino スケッチに含めます。#include <SPI.h> #include <WiFi101.h> #include <PubSubClient.h> #include "DHT.h"
センサーに接続された Arduino ボード ピンを定義します。
#define DHTPIN 2 // DHT Sensor connected to digital pin 2. #define DHTTYPE DHT11 // Type of DHT sensor. #define LIGHTPIN A0 // Analog light sensor connected to analog pin A0. DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.
Arduino ボードをネットワークに接続するためのワイヤレス ネットワーク資格情報を定義し、WiFi クライアント ライブラリを初期化します。
char ssid[] = "YOUR-NETWORK-SSID"; // Change this to your network SSID (name). char pass[] = "YOUR-NETWORK-PWD"; // Change this your network password char mqttUserName[] = "TSArduinoMQTTDemo"; // Can be any name. char mqttPass[] = "YOURMQTTAPIKEY"; // Change this your MQTT API Key from Account > MyProfile. char writeAPIKey[] = "XXXXXXXXXXXXXXXX"; // Change to your channel Write API Key. long channelID = NNNNNN; static const char alphanum[] ="0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; // For random generation of client ID. WiFiClient client; // Initialize the Wifi client library.
部分的に初期化された
PubSubClient
インスタンスを作成し、ThingSpeak MQTT ブローカーを定義します。WiFiClient client; // Initialize the Wifi client library. PubSubClient mqttClient(client); // Initialize the PuBSubClient library. const char* server = "mqtt.thingspeak.com";
他のグローバル変数を定義して最後の接続時間を追跡し、データをパブリッシュする時間間隔を定義します。
unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 20L * 1000L; // Post data every 20 seconds.
setup
メソッドでシリアル データ転送を初期化し、ワイヤレス ネットワークに接続し、MQTT ブローカーの詳細を設定します。void setup() { Serial.begin(9600); int status = WL_IDLE_STATUS; // Set a temporary WiFi status. // Attempt to connect to WiFi network while (status != WL_CONNECTED) { status = WiFi.begin(ssid, pass); // Connect to WPA/WPA2 Wi-Fi network. delay(5000); } Serial.println("Connected to wifi"); mqttClient.setServer(server, 1883); // Set the MQTT broker details. }
loop
メソッドで MQTT 接続を確立し、データを一定の時間間隔でチャネルにパブリッシュします。void loop() { // Reconnect if MQTT client is not connected. if (!mqttClient.connected()) { reconnect(); } mqttClient.loop(); // Call the loop continuously to establish connection to the server. // If interval time has passed since the last connection, Publish data to ThingSpeak if (millis() - lastConnectionTime > postingInterval) { mqttpublish(); } }
Arduino クライアントを MQTT ブローカーと接続するように
reconnect
メソッドを定義します。void reconnect() { char clientID[10]; // Loop until we're reconnected while (!mqttClient.connected()) { Serial.print("Attempting MQTT connection..."); // Generate ClientID for (int i = 0; i < 8; i++) { clientID[i] = alphanum[random(51)]; } // Connect to the MQTT broker if (mqttClient.connect(clientID,mqttUserName,mqttPass)) { Serial.println("connected"); } else { Serial.print("failed, rc="); // Print to know why the connection failed. // See http://pubsubclient.knolleary.net/api.html#state for the failure code explanation. Serial.print(mqttClient.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } }
センサー データを ThingSpeak チャネル フィードにパブリッシュするように
mqttpublish
メソッドを定義します。チャネル フィードにパブリッシュする場合は、一度に複数のフィールドにパブリッシュできます。ここでは、チャネルの Field 1、2、および 3 にパブリッシュします。void mqttpublish() { float t = dht.readTemperature(true); // Read temperature from DHT sensor. float h = dht.readHumidity(); // Read humidity from DHT sensor. int lightLevel = analogRead(LIGHTPIN); // Read from light sensor // Create data string to send to ThingSpeak String data = String("field1=" + String(t, DEC) + "&field2=" + String(h, DEC) + "&field3=" + String(lightLevel, DEC)); int length = data.length(); char msgBuffer[length]; data.toCharArray(msgBuffer,length+1); Serial.println(msgBuffer); // Create a topic string and publish data to ThingSpeak channel feed. String topicString ="channels/" + String( channelID ) + "/publish/"+String(writeAPIKey); length=topicString.length(); char topicBuffer[length]; topicString.toCharArray(topicBuffer,length+1); mqttClient.publish( topicBuffer, msgBuffer ); lastConnectionTime = millis(); } // Use this function instead to publish to a single field directly. Don't forget to comment out the above version. /* void mqttpublish() { float t = dht.readTemperature(true); // Read temperature from DHT sensor. String data = String(t, DEC); int length = data.length(); char msgBuffer[length]; data.toCharArray(msgBuffer,length+1); Serial.println(msgBuffer); // Create a topic string and publish data to ThingSpeak channel feed. String topicString ="channels/" + String( channelID ) + "/publish/"+String(writeAPIKey); length=topicString.length(); char topicBuffer[length]; topicString.toCharArray(topicBuffer,length+1); mqttClient.publish( topicBuffer, msgBuffer ); lastConnectionTime = millis(); } */
参考
Publish to a Channel Field Feed | Publish to a Channel Feed
関連する例
- デスクトップ MQTT クライアントを使用したチャネルへのパブリッシュ
- Particle Photon クライアントを使用したパブリッシュ
- Raspberry Pi 上の Python で WebSocket を使用したパブリッシュ