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.

Publish Using Particle Photon Client

This example shows how to use a Particle Photon board with 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, if you have only one sensor, you can publish a single value to a channel field.

 Full Code

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

  2. Include the libraries MQTT/MQTT.h and Adafruit_DHT/Adafruit_DHT.h to your Particle IDE. Do not add this text yourself, the text appears automatically when you include the library.

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

  3. Define the sensor pins used on your Particle Photon board.

    #define DHTPIN 2                             // DHT Sensor connected to digital pin 2.
    #define DHTTYPE DHT11
    #define LIGHTPIN A0                          // Analog light sensor connected to analog pin A0.

  4. Define the variables used to communicate with ThingSpeak. Change the mqttPass to be your MQTT API Key, which can be found under Account > MyProfile. Change the writeAPIKey to be the Write API Key for your channel, and enter the channel number for channelID.

    char mqttUserName[] = "TSPhotonMQTTDemo";    // Can be any name.
    char mqttPass[] = "XXXXXXXXXXXXXXXX";        // Change this to your MQTT API Key from Account > MyProfile.
    char writeAPIKey[] = "YYYYYYYYYYYYYYYY";     // Change this to your channel Write API Key.
    long channelID = 123456;                     // Change this to your channel number.
    char server[] = "mqtt.thingspeak.com";       // Define the ThingSpeak MQTT broker
    static const char alphanum[] ="0123456789"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz";                // This variable is used for random generation of client ID.
  5. Define a callback function for the MQTT client and initialize the DHT sensor and the client.

    // Define a callback function to initialize the MQTT client.
    void callback(char* topic, byte* payload, unsigned int length) {
     }
    
    DHT dht(DHTPIN, DHTTYPE);                  // Initialize DHT sensor.
    MQTT client(server, 1883, callback);       // Initialize the MQTT client.

  6. Track the last connection time and define the publish data time interval with global variables.

    unsigned long lastConnectionTime = 0;
    const unsigned long postingInterval = 20L * 1000L; // Post data every 20 seconds. 

  7. Initialize the input pins for the DHT sensor in the setup method.

    void setup() {
        
        pinMode(DHTPIN, INPUT);
        
    }

  8. Establish the MQTT connection and publish data to the channel at regular time intervals in the main loop method.

    void loop() {
        
        // If MQTT client is not connected then reconnect.
        if (!client.isConnected())
        {
          reconnect();
        }
        
        client.loop();  // Call the loop continuously to establish connection to the server.
        
        if (millis() - lastConnectionTime > postingInterval)
        {
            mqttpublish();
        }
    }

  9. Generate a unique client ID and connect the Particle Photon MQTT client to the ThingSpeak MQTT broker with the reconnect method.

    void reconnect(){
        
         char clientID[9];
         
         Serial.println("Attempting MQTT connection");
            // Generate ClientID
            for (int i = 0; i < 8; i++) {
                clientID[i] = alphanum[random(51)];
            }
            clientID[8]='\0';
            
            // Connect to the ThingSpeak MQTT broker.
            if (client.connect(clientID,mqttUserName,mqttPass))  {
                Particle.publish("Conn:"+ String(server) + " cl: " + String(clientID)+ " Uname:" + String(mqttUserName));
            } else
            {
                Particle.publish("Failed to connect, Trying to reconnect in 5 seconds");
                delay(5000);
            } 
    }

  10. Publish the sensor data to the ThingSpeak channel feed using the mqttpublish method. If you are publishing to the channel feed, you can publish to multiple fields at once. This case publishes to fields 1, 2, and 3 of the channel. If you have only one sensor, you can publish to a single field directly. The syntax is commented in the code shown here. To publish to a single field directly, switch the comments on the two lines beginning with String.

    void mqttpublish() {
        
        float t = dht.getTempFarenheit(); // Read temperature from DHT sensor.
        float h = dht.getHumidity();  // Read humidity from DHT sensor.
        int lightLevel = analogRead(LIGHTPIN); // Read from light sensor.
        
        // Create data string to send data to ThingSpeak.
        // Use these lines to publish to a channel feed,
        // which allows multiple fields to be updates simultaneously.
        // Comment these lines and use the next two to publish to a single channel field directly.
        String data = String("field1=" + String(t) + "&field2=" + String(h) + "&field3=" + String(lightLevel));
        String topic = String("channels/"+String(channelID)+ "/publish/"+String(writeAPIKey));
        
        //String data=String(t);
        //String topic = String("channels/"+String(channelID)+ "/publish/fields/field1/"+String(writeAPIKey));
        
        client.publish(topic,data);
        
        lastConnectionTime = millis();
    }

See Also

|

Related Examples

More About

Was this topic helpful?