Main Content

このページの翻訳は最新ではありません。ここをクリックして、英語の最新版を参照してください。

Arduino MKR1000 ボードまたは ESP8266 ボードを使用して継続的にデータを収集し、ThingSpeak チャネルを一括更新

この例では、Wi-Fi® ネットワークに接続された Arduino® MKR1000 ボードまたは ESP8266 ボードのいずれかを使用して、Wi-Fi 信号の強度を継続的に収集し、ThingSpeak™ チャネルを一括更新する方法を説明します。チャネル フィードの一括更新API を使用してデータをバッチとして収集し、ThingSpeak チャネルに送信することができます。この方法により、デバイスの電力使用量が節減されます。この例では、Arduino MKR1000 ボードを使用して 15 秒に 1 回データを収集し、 2 分に 1 回チャネルを更新します。Arduino MKR1000 および ESP8266 ボードにはリアルタイム クロックがないため、一括更新メッセージに相対タイム スタンプを使用しなければならない場合があります。

 チャネル フィードを一括更新する Arduino コード

  1. 新しいチャネルでデータの収集での説明に従ってチャネルを作成します。

  2. Arduino MKR1000 ボードを使用している場合は、WiFi101.h ライブラリと SPI.h ライブラリを Arduino スケッチに含めます。ESP8266 ボードを使用している場合は、EthernetClient.h ライブラリと ESP8266WiFi.h ライブラリを Arduino スケッチに含めます。

    // #include<EthernetClient.h> //Uncomment this library to work with ESP8266
    // #include<ESP8266WiFi.h> //Uncomment this library to work with ESP8266
    
    #include<SPI.h> // Comment this to work with ESP8266 board
    #include<WiFi101.h> // Comment this to work with ESP8266 board
    

  3. JSON データを格納する jsonBuffer を初期化します。

    char jsonBuffer[500] = "["; // Initialize the jsonBuffer to hold data

  4. Arduino ボードをネットワークに接続するための WiFi 資格情報を定義し、WiFi クライアント ライブラリを初期化します。

    char ssid[] = "YOUR-NETWORK-SSID"; //  Your network SSID (name)
    char pass[] = "YOUR-NETWORK-PWD"; // Your network password
    WiFiClient client; // Initialize the WiFi client library
    

  5. ThingSpeak サーバーを定義します。

    char server[] = "api.thingspeak.com"; // ThingSpeak Server
    

  6. 他のグローバル変数を定義して、最終接続日時と最終更新日時を追跡します。また、データを更新する時間間隔を定義し、データを ThingSpeak にポストします。

    /* Collect data once every 15 seconds and post data to ThingSpeak channel once every 2 minutes */
    unsigned long lastConnectionTime = 0; // Track the last connection time
    unsigned long lastUpdateTime = 0; // Track the last update time
    const unsigned long postingInterval = 120L * 1000L; // Post data every 2 minutes
    const unsigned long updateInterval = 15L * 1000L; // Update once every 15 seconds
    

  7. シリアル データ転送を初期化して WiFi ネットワークに接続するために、setup メソッドをオーバーライドします。

    void setup() {
      Serial.begin(9600);
      // Attempt to connect to WiFi network
      while (WiFi.status() != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        WiFi.begin(ssid, pass);  // Connect to WPA/WPA2 network. Change this line if using open or WEP network
        delay(10000);  // Wait 10 seconds to connect
      }
      Serial.println("Connected to wifi");
      printWiFiStatus(); // Print WiFi connection information
    }
    

  8. updatesJson メソッドを呼び出して 1 秒ごとに jsonBuffer のデータを更新するために、loop メソッドをオーバーライドします。

    void loop() {
      // If update time has reached 1 second, then update the jsonBuffer
      if (millis() - lastUpdateTime >=  updateInterval) {
        updatesJson(jsonBuffer);
      }
        
    }
    

  9. jsonBuffer のデータで継続的に更新するために、updatesJson メソッドを定義します。Arduino MKR1000 にはリアルタイム クロックがないため、'delta_t' パラメーターを使用して、連続するメッセージ間の秒数を相対タイム スタンプで定義します。デバイスにリアルタイム クロックがある場合は、絶対タイムスタンプを使用できます。'delta_t' パラメーターを 'created_at' パラメーターに置き換えます。チャネル フィードの一括更新で説明されている形式で、メッセージを JSON として書式設定します。2 分に 1 回 httpRequest メソッドを呼び出して、データを ThingSpeak に送信します。

    // Updates the josnBuffer with data
    void updatesJson(char* jsonBuffer){
      /* JSON format for updates paramter in the API
       *  This examples uses the relative timestamp as it uses the "delta_t". You can also provide the absolute timestamp using the "created_at" parameter
       *  instead of "delta_t".
       *   "[{\"delta_t\":0,\"field1\":-70},{\"delta_t\":3,\"field1\":-66}]"
       */
      // Format the jsonBuffer as noted above
      strcat(jsonBuffer,"{\"delta_t\":");
      unsigned long deltaT = (millis() - lastUpdateTime)/1000;
      size_t lengthT = String(deltaT).length();
      char temp[4];
      String(deltaT).toCharArray(temp,lengthT+1);
      strcat(jsonBuffer,temp);
      strcat(jsonBuffer,",");
      long rssi = WiFi.RSSI(); 
      strcat(jsonBuffer, "\"field1\":");
      lengthT = String(rssi).length();
      String(rssi).toCharArray(temp,lengthT+1);
      strcat(jsonBuffer,temp);
      strcat(jsonBuffer,"},");
      // If posting interval time has reached 2 minutes, update the ThingSpeak channel with your data
      if (millis() - lastConnectionTime >=  postingInterval) {
            size_t len = strlen(jsonBuffer);
            jsonBuffer[len-1] = ']';
            httpRequest(jsonBuffer);
      }
      lastUpdateTime = millis(); // Update the last update time
    }
    

  10. ThingSpeak にデータを送信し、サーバーからの応答コードを出力するために、httpRequest メソッドを定義します。応答コード 202 は、サーバーで要求が受け入れられたことと、その要求が処理されることを示します。

    // Updates the ThingSpeakchannel with data
    void httpRequest(char* jsonBuffer) {
      /* JSON format for data buffer in the API
       *  This examples uses the relative timestamp as it uses the "delta_t". You can also provide the absolute timestamp using the "created_at" parameter
       *  instead of "delta_t".
       *   "{\"write_api_key\":\"YOUR-CHANNEL-WRITEAPIKEY\",\"updates\":[{\"delta_t\":0,\"field1\":-60},{\"delta_t\":15,\"field1\":200},{\"delta_t\":15,\"field1\":-66}]
       */
      // Format the data buffer as noted above
      char data[500] = "{\"write_api_key\":\"YOUR-CHANNEL-WRITEAPIKEY\",\"updates\":"; // Replace YOUR-CHANNEL-WRITEAPIKEY with your ThingSpeak channel write API key
      strcat(data,jsonBuffer);
      strcat(data,"}");
      // Close any connection before sending a new request
      client.stop();
      String data_length = String(strlen(data)+1); //Compute the data buffer length
      Serial.println(data);
      // POST data to ThingSpeak
      if (client.connect(server, 80)) {
        client.println("POST /channels/YOUR-CHANNEL-ID/bulk_update.json HTTP/1.1"); // Replace YOUR-CHANNEL-ID with your ThingSpeak channel ID
        client.println("Host: api.thingspeak.com");
        client.println("User-Agent: mw.doc.bulk-update (Arduino ESP8266)");
        client.println("Connection: close");
        client.println("Content-Type: application/json");
        client.println("Content-Length: "+data_length);
        client.println();
        client.println(data);
      }
      else {
        Serial.println("Failure: Failed to connect to ThingSpeak");
      }
      delay(250); //Wait to receive the response
      client.parseFloat();
      String resp = String(client.parseInt());
      Serial.println("Response code:"+resp); // Print the response code. 202 indicates that the server has accepted the response
      jsonBuffer[0] = '['; //Reinitialize the jsonBuffer for next batch of data
      jsonBuffer[1] = '\0';
      lastConnectionTime = millis(); //Update the last conenction time
    }
    
    

  11. デバイスの IP アドレスと信号強度を出力する printWiFiStatus メソッドを定義します。

    void printWiFiStatus() {
      // Print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());
    
      // Print your device IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);
    
      // Print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }
    

関連する例

詳細