Implementing the weather data collection project

After setting up your Arduino IDE, paste the following code into it. Change the mqttPass with your MQTT Username, Password, Channel ID with the ones for your channel and device.

#include <PubSubClient.h>
#include <Ethernet.h>
#include <EthernetClient.h>

#include <Wire.h>
#include <Sodaq_SHT2x.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(109, 74, 198, 92);
IPAddress myDns(8, 8, 8, 8);

char mqttUserName[] = "";  // MQTT Client ID of your device
char mqttPass[] = "";      // Change to your MQTT Password generated when creating the device on ThingSpeak
long channelID = 0;        // Change to your channel ID.

EthernetClient client;                         // Initialize the Wi-Fi client library.

PubSubClient mqttClient(client); // Initialize the PubSubClient library.
const char* server = "mqtt3.thingspeak.com";

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

void setup() {
  Wire.begin();
  Serial.begin(9600);

  Ethernet.begin(mac, ip, myDns);
  delay(1000); //give the ethernet a second to initialize
  mqttClient.setServer(server, 1883);   // Set the MQTT broker details.
}

void loop() {
  // Reconnect if MQTT client is not connected.
  if (!mqttClient.connected())
  {
    reconnect();
  }

  mqttClient.loop();   // Call the loop continuously to establish connection to the server.

  // If interval time has passed since the last connection, publish data to ThingSpeak.
  if (millis() - lastConnectionTime > postingInterval)
  {
    mqttPublishFeed(); // Publish three values simultaneously.
    // mqttPublishField(fieldNumber); // Use this function to publish to a single field
  }
}
void reconnect()
{
  
  // Loop until reconnected.
  while (!mqttClient.connected())
  {
    Serial.print("Attempting MQTT connection...");

    // Connect to the MQTT broker.
    if (mqttClient.connect(mqttUserName, mqttUserName, mqttPass))
    {
      Serial.println("connected");
    } else
    {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void mqttPublishFeed() {

  float h = SHT2x.GetHumidity();
  float t = SHT2x.GetTemperature();

  // Create data string to send to ThingSpeak.
  String data = "field1=" + String(t) + "&field2=" + String(h)+ "&status=MQTTPUBLISH";
  int length = data.length();
  const char *msgBuffer;
  msgBuffer = data.c_str();
  Serial.println(msgBuffer);

  // Create a topic string and publish data to ThingSpeak channel feed.
  String topicString = "channels/" + String( channelID ) + "/publish";
  length = topicString.length();
  const char *topicBuffer;
  topicBuffer = topicString.c_str();
  mqttClient.publish( topicBuffer, msgBuffer );
  lastConnectionTime = millis();
}

Now we need to export the Compiled Binary for this program. Go to Sketch and select Export Compiled Binary. This should save a hex file at the location you have saved this sketch. Now go back to Simuli Virtual Lab and open the new instance we had created for this project. Our workspace will now open. Upload the sketch_name.ino.standard.hex file by clicking on the Arduino and navigating to where the sketch was stored. Now we just need to reset the Arduino and the program will be loaded.

The Arduino will now automatically connect to ThingSpeak and start sending the sensor data. We can see the output of the data in our channel on ThingSpeak. As we change the sensor values, it will also be reflected in the graphs on the channel.

The Arduino may take a few seconds to connect to the MQTT broker, and may initially show errors. If it fails to connect to the MQTT broker even after a minute, reset the Arduino.

We have successfully completed this project. Now you know how to use the Arduino Uno with the W5500 to connect to an MQTT broker and publish the real-time sensor data.

ThingSpeak also allows you to analyse your data with MATLAB and create powerful visualisations from the raw data. However, that is beyond the scope of this guide. MathWorks provides a good guide with example codes to get you started. You can follow this link to learn How to Visualise the Correlation Between Temperature and Humidity using MATLAB.

Last updated