This is machine translation

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

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Publish Using Particle Photon Client

This example shows how to publish measured values to a ThingSpeak channel. In the example, you use a Particle Photon board with a DHT11 sensor to measure temperature and humidity and an analog light sensor to measure light intensity. 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.

Set Up

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

Code

1) Include the libraries MQTT/MQTT.h and Adafruit_DHT/Adafruit_DHT.h in your Particle IDE.

2) Define the sensor pins used on your Particle Photon board. For this example, connect the DHT sensor to digital pin 2 and the analog light sensor to analog pin A0.

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

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

char mqttUserName[] = "TSPhotonMQTTDemo";    // Use 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 the client ID.

4) 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 the DHT sensor.
MQTT client(server, 1883, callback);       // Initialize the MQTT client.

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

unsigned long lastConnectionTime = 0;toolboc
const unsigned long postingInterval = 20L * 1000L; // Post data every 20 seconds. 
Initialize the input pins for the DHT sensor in the setup method.

6) Initialize the input pins for the DHT sensor in the setup method.

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

6) Establish the MQTT connection and publish data to the channel at regular time intervals in the main loop function.

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

7) Generate a unique client ID and connect the Particle Photon MQTT client to the ThingSpeak MQTT broker with the reconnect function.

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

8) 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 code 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 comment 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 voltage from light sensor.
    
    // Create a data string to send data to ThingSpeak.
    // Use these lines to publish to a channel feed,
    // which allows multiple fields to be updated 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