Main Content

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.


  • This example requires the Adafruit_DHT version 0.02 library for use with a Particle Photon or Electron. If you install the latest Adafruit_DHT library, you must downgrade to version 0.02 for these devices.

  • Adafruit_DHT version 0.04 works with a Particle Argon or Boron.

Set Up

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


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[] = "";       // Define the ThingSpeak MQTT broker.
static const char alphanum[] ="0123456789"
"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;
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);

7) 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())
    client.loop();  // Call the loop continuously to establish connection to the server.
    if (millis() - lastConnectionTime > postingInterval)

8) 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)];
        // 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");

9) 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));
    lastConnectionTime = millis();

See Also


Related Examples

More About