Main Content

Cette page a été traduite par traduction automatique. Cliquez ici pour voir la dernière version en anglais.

Mise à jour en masse à l'aide d'un Arduino ou d'un ESP8266

Cet exemple montre comment utiliser une carte Arduino® MKR1000 ou une carte ESP8266 connectée à un réseau Wi-Fi® pour collecter en continu la force du signal Wi-Fi et mettre à jour en bloc un canal ThingSpeak ™.

Vous pouvez utiliser l'API Bulk-Write JSON Data pour collecter des données par lots et les envoyer aux canaux ThingSpeak . Cette stratégie réduit la consommation d'énergie de vos appareils. Dans cet exemple, vous collectez des données une fois toutes les 15 secondes et mettez à jour votre canal une fois toutes les 2 minutes à l'aide d'une carte Arduino MKR1000. Étant donné que l'Arduino MKR1000 et la carte ESP8266 n'ont pas d'horloge en temps réel, vous pouvez utiliser l'horodatage relatif pour les messages de mise à jour en masse.

Installation

  1. Créez un canal comme indiqué dans Collecter des données dans un nouveau canal.

  2. Si vous utilisez une carte Arduino MKR1000, incluez les bibliothèques WiFi101.h et SPI.h à votre figure Arduino. Si vous utilisez une carte ESP8266, incluez les bibliothèques EthernetClient.h et ESP8266WiFi.h à votre figure Arduino

Code

1) Commencez par inclure les bibliothèques appropriées pour votre hardware.

// #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

2) Initialisez le jsonBuffer pour contenir les données JSON.

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

3) Définissez les informations d'identification Wi-Fi pour connecter votre carte Arduino au réseau et initialisez la bibliothèque client Wi-Fi.

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

4) Définissez le serveur ThingSpeak .

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

5) Définissez d'autres variables globales qui suivent l'heure de la dernière connexion et l'heure de la dernière mise à jour. Définissez également des intervalles de temps pour mettre à jour les données et publiez les données sur 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

6) Utilisez la méthode setup pour initialiser le transfert de données série et vous connecter au réseau Wi-Fi.

void setup() {
  Serial.begin(9600);
  // Attempt to connect to Wi-Fi 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 Wi-Fi");
  printWiFiStatus(); // Print Wi-Fi connection information
}

7) Dans la méthode loop, appelez la méthode updatesJson pour mettre à jour le jsonBuffer avec les données une fois par seconde.

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

8) Définissez la méthode updatesJson pour mettre à jour en continu le jsonBuffer avec les données. L'Arduino MKR1000 n'ayant pas d'horloge temps réel, vous utilisez le paramètre 'delta_t' pour définir un horodatage relatif en secondes entre les messages successifs. Si votre appareil dispose d'une horloge en temps réel, vous pouvez utiliser un horodatage absolu. Remplacez le paramètre 'delta_t' par le paramètre 'created_at'. Formatez les messages au format JSON dans un format mentionné dans Bulk-Write JSON Data. Appelez la méthode httpRequest pour envoyer des données à ThingSpeak une fois toutes les 2 minutes.

// Updates the josnBuffer with data
void updatesJson(char* jsonBuffer){
  /* JSON format for updates parameter in the API
   *  This example 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
}

9) Définissez la méthode httpRequest pour envoyer des données à ThingSpeak et imprimer le code de réponse du serveur. Un code de réponse 202 indique que le serveur a accepté la demande de précession.

// Updates the ThingSpeakchannel with data
void httpRequest(char* jsonBuffer) {
  /* JSON format for data buffer in the API
   *  This example 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
}

10) Définissez la méthode printWiFiStatus pour imprimer l'adresse IP et la force du signal de votre appareil .

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");
}

Exemples associés

En savoir plus