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 Particle Photon Client to Publish to a Channel

This example shows how to use a Particle Photon 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 Particle Code to Publish to a Channel Feed

 Click Here for Particle Code to Publish to a Channel Field

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

  2. Download and include the libraries MQTT/MQTT.h and Adafruit_DHT/Adafruit_DHT.h to your Particle IDE.

    #include "Adafruit_DHT/Adafruit_DHT.h"
    #include "MQTT/MQTT.h"

  3. Define the macros to initialize the sensors connected to your Particle Photon 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 Particle Photon board to the network.

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

    // Define a callback function to initialize the MQTT client
    void callback(char* topic, byte* payload, unsigned int length) {
        Serial.println("Call back definition");
    }
    // Initialize the MQTT client
    MQTT client(server, 1883, callback);
    // Define the ThingSpeak MQTT broker
    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 connect to the MQTT broker.

    void setup() {
      // Begin serial transfer
       Serial.begin(9600);
       // Set the wifi credentials
       wifisetup();
       // Set the digital pin 2 mode to input
        pinMode(DHTPIN, INPUT);
        // Connect to the ThingSpeak MQTT broker
        client.connect("sparkclient");
    }
    

  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 (!client.isConnected())
        {
            Serial.println("Attempting MQTT connection");
            // Connect to the ThingSpeak MQTT broker
            if (client.connect("sparkclient")) {
                Serial.println("Connected");
            } else
            {
                Serial.println("Failed to connect");
                Serial.println("Trying to reconnect in 5 seconds");
                delay(5000);
            }
        }
        
        // Call the loop continuously to establish connection to the server
        client.loop();
        if (millis() - lastConnectionTime > postingInterval) 
        {
            mqttpublish();
        }
    }

  9. Define the wifisetup method to connect the Particle Photon board to WiFi.

    void wifisetup() {
        // Set the wifi credentials
        WiFi.setCredentials(ssid, pass);
        bool status = true;
        while(status){
            // Attempt to connect to wifi network
            Serial.println("Connecting to wifi");
            WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);
            if(!WiFi.ready()){
                Serial.println("Failed to connect");
                // Wait 10 seconds for reconnection
                delay(10000);
            }
            Serial.println("Connected to wifi");
            status = false;
        }
        
    }

  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.getTempFarenheit();
        // Read humidity from DHT sensor
        float h = dht.getHumidity();
        // Read from light sensor
        int lightlevel = analogRead(LIGHTPIN);
        // Create data string to send data to ThingSpeak
        String data = String("field1=" + String(t) + "&field2=" + String(h) + "&field3=" + String(lightlevel));
        // Print payload to serial monitor
        Serial.println(data);
        // Publish data to ThingSpeak. Replace <YOUR-CHANNEL-ID> with your channel ID and <YOUR-CHANNEL-WRITEAPIKEY> with your write API key
        client.publish("channels/<YOUR-CHANNEL-ID>/publish/<YOUR-CHANNEL-WRITEAPIKEY>",data);
        // 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 as shown in this case where we publish to field 1 of the channel.

    void mqttpublish() {
      // Read temperature from DHT sensor
      float t = dht.getTempFarenheit();
      String data = String(t);
      // Publish data to ThingSpeak. Replace <YOUR-CHANNEL-ID> with your channel ID and <YOUR-CHANNEL-WRITEAPIKEY> with your write API key
      client.publish("channels/<YOUR-CHANNEL-ID>/publish/fields/field1/<YOUR-CHANNEL-WRITEAPIKEY>",data);
      // note the last connection time
      lastConnectionTime = millis();
    }

See Also

|

Related Examples

More About

Was this topic helpful?