ThingSpeak

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

Use Arduino Client to Publish to a Channel

This example shows how to use an Arduino® MKR1000 board connected to a DHT11 sensor that measures temperature and humidity and an analog light sensor that measures the light intensity. The measured values are published to a ThingSpeak™ channel. If you have more than one sensor value that you want to send to ThingSpeak, you can choose to publish multiple values to a channel feed . Alternatively, you can publish a single value to a channel field if you have only one sensor.

 Click Here for Arduino Code to Publish to a Channel Feed

 Click Here for Arduino Code to Publish to a Channel Field

  1. Create a Channel as shown in Collect Data in a New Channel.

  2. Download the libraries WiFi101.h and DHT.h to your Arduino IDE. Include the libraries SPI.h, WiFi101.h, PubSubClient.h, and DHT.h to your Arduino sketch.

    #include <SPI.h>
    #include <WiFi101.h>
    #include <PubSubClient.h>
    #include "DHT.h"

  3. Define the macros to initialize the sensors connected to your Arduino board.

    // DHT Sensor connected to digital pin 2
    #define DHTPIN 2 
    // Type of DHT sensor
    #define DHTTYPE DHT11 
    // Analog light sensor connected to analog pin A0
    #define LIGHTPIN A0 
    // Initialize DHT sensor
    DHT dht(DHTPIN, DHTTYPE);

  4. Define the WiFi credentials to connect your Arduino board to the network, and initialize the WiFi client library.

    //  your network SSID (name)
    char ssid[] = "YOUR-NETWORK-SSID"; 
    // your network password
    char pass[] = "YOUR-NETWORK-PWD"; 
    // Initialize the Wifi client library
    WiFiClient client;
  5. Create a partially initialized PubSubClient instance, and define the ThingSpeak MQTT broker.

    // Initialize the PuBSubClient library
    PubSubClient mqttClient(client);
    // Define the ThingSpeak MQTT broker
    const char* server = "mqtt.thingspeak.com";

  6. Define other global variables to track the last connection time and to define the time interval to publish the data.

    // track the last connection time
    unsigned long lastConnectionTime = 0; 
    // post data every 20 seconds
    const unsigned long postingInterval = 20L * 1000L; 

  7. Override the setup method to initialize serial data transfer, to connect to WiFi network, and to set the MQTT broker details.

    void setup() {
      // Begin serial transfer
      Serial.begin(9600);
      // Set a temporary WiFi status
      int status = WL_IDLE_STATUS;
      // Attempt to connect to WiFi network
      while (status != WL_CONNECTED) 
      {
        // Connect to WPA/WPA2 Wi-Fi network
        status = WiFi.begin(ssid, pass);
    
        // Wait 10 seconds for connection
        delay(10000);
      }
      Serial.println("Connected to wifi");
      // Set the MQTT broker details
      mqttClient.setServer(server, 1883);
    }
    

  8. Override the loop method to establish MQTT connection, and publish data to the channel at regular time intervals.

    void loop() {
     // Check if MQTT client has connected else reconnect
      if (!mqttClient.connected()) 
      {
        reconnect();
      }
      // Call the loop continuously to establish connection to the server
      mqttClient.loop();
      // If interval time has passed since the last connection, Publish data to ThingSpeak
      if (millis() - lastConnectionTime > postingInterval) 
      {
        mqttpublish();
      }
    }

  9. Define the reconnect method to connect the Arduino client with the MQTT broker.

    void reconnect() 
    {
      // Loop until we're reconnected
      while (!mqttClient.connected()) 
      {
        Serial.print("Attempting MQTT connection...");
        // Connect to the MQTT broker
        if (mqttClient.connect("ArduinoWiFi101Client")) 
        {
          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 and its reason
          Serial.print(mqttClient.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying to connect again
          delay(5000);
        }
      }
    }

  10. Define the mqttpublish method to publish the sensor data to the ThingSpeak channel feed. You can publish to multiple fields at once if you are publishing to the channel feed, as shown in this case that publishes to fields 1, 2, and 3 of the channel.

    void mqttpublish() {
      // Read temperature from DHT sensor
      float t = dht.readTemperature(true);
      // Read humidity from DHT sensor
      float h = dht.readHumidity();
      // Read from light sensor
      int lightLevel = analogRead(LIGHTPIN);
      // Create data string to send to ThingSpeak
      String data = String("field1=" + String(t, DEC) + "&field2=" + String(h, DEC) + "&field3=" + String(lightLevel, DEC));
      // Get the data string length
      int length = data.length();
      char msgBuffer[length];
      // Convert data string to character buffer
      data.toCharArray(msgBuffer,length+1);
      Serial.println(msgBuffer);
      // Publish data to ThingSpeak. Replace <YOUR-CHANNEL-ID> with your channel ID and <YOUR-CHANNEL-WRITEAPIKEY> with your write API key
      mqttClient.publish("channels/<YOUR-CHANNEL-ID>/publish/<YOUR-CHANNEL-WRITEAPIKEY>",msgBuffer);
      // note the last connection time
      lastConnectionTime = millis();
    }

    Alternatively, if you want to publish only to a single field in a channel, you can publish to a channel field.

    void mqttpublish() {
      // Read temperature from DHT sensor
      float t = dht.readTemperature(true);
      String data = String(t, DEC);
      // Get the data string length
      int length = data.length();
      char msgBuffer[length];
      // Convert data string to character buffer
      data.toCharArray(msgBuffer,length+1);
      Serial.println(msgBuffer);
      // Publish data to ThingSpeak. Replace <YOUR-CHANNEL-ID> with your channel ID and <YOUR-CHANNEL-WRITEAPIKEY> with your write API key
      mqttClient.publish("channels/<YOUR-CHANNEL-ID>/publish/fields/field1/<YOUR-CHANNEL-WRITEAPIKEY>",msgBuffer);
      // note the last connection time
      lastConnectionTime = millis();
    }

See Also

|

Related Examples

More About

Was this topic helpful?