Main Content

Publish to a ThingSpeak Channel Using a Particle Device Client via MQTT

This example shows how to publish measured values to a ThingSpeak channel via MQTT using a Particle device such as a Boron, Argon, Photon, or Electron. If you have more than one value to send to ThingSpeak, you can 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

1) Create a new channel, as shown in Collect Data in a New Channel. Be sure to enable all the fields that you plan to use.

2) Create an MQTT device by clicking Devices > MQTT at the top of the ThingSpeak page, then Add Device. When setting up the device and adding the new channel to its authorized list, click Download Credentials > Plain Text. Use the saved credentials in the Code section below. For details, see Create a ThingSpeak MQTT Device.

3) Include the library MQTT/MQTT.h in your Particle IDE.

Code

1) Define the variables used to communicate with ThingSpeak. Edit the code for your own IDs and credentials.

// This #include statement is automatically added by the Particle IDE.
#include <MQTT.h>

const long channelId = YOUR_THINGSPEAK_CHANNEL_NUMBER; // Change this to your ThingSpeak channel number.
String clientId = "MQTT_CLIENDID_FROM_THINGSPEAK";
String username = "MQTT_USERNAME_FROM_THINGSPEAK";
String password = "MQTT_PASSWORD_FROM_THINGSPEAK";
char server[] = "mqtt3.thingspeak.com";

2) Track the last connection time and define the publish data time interval with global variables. Initialize the MQTT client.

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

int strength = WiFi.RSSI();
int power = 10^(strength/10);

MQTT client(server, 1883, callback);               // Initialize the MQTT client.

3) Define a callback function for the MQTT client. In this case, the setup function is deliberately empty.

// Define a callback function to initialize the MQTT client.
void callback(char* topic, byte* payload, unsigned int length) {
}
void setup() {
}

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

5) 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. If you have only one sensor, you can publish to a single field directly. Alter the line commenting in the following code as needed.

void mqttpublish() {
    
    //Get SSID signal strength
    strength = WiFi.RSSI();
    
    //Power in milliwatts
    power = 10^(strength/10);
    
    // 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.
    // String data = String("field1=" + String(strength) + "&field2=" + String(power) );
    // String topic = String("channels/"+String(channelId)+ "/publish");
    
    // Use the next two to publish to a single channel field directly.
    String data = String(strength);
    String topic = String("channels/"+String(channelId)+ "/publish/fields/field1");
    
    client.publish(topic,data);
    
    lastConnectionTime = millis();
}

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

void reconnect(){
    
    Particle.publish("Attempting MQTT connection");
        
    // Connect to the ThingSpeak MQTT broker.
    if (client.connect(clientId,username,password))  {
        // Track the connection with particle console.
        Particle.publish("Conn:"+ String(server) + " cl: " + String(clientId)+ " Uname:" + String(username));
    } else {
        Particle.publish("Failed to connect. Trying to reconnect in 2 seconds");
        delay(2000);
    } 
}

See Also

|

Related Examples

More About