Skip to main content

How to use Node js to interact with IIOT platform without iot device

· 5 min read

In this tutorial, we'll demonstrate an experiment using a Node.js script to interact with the IIOT platform via MQTT. This script will show how to connect to an MQTT broker, publish sensor data (temperature and humidity) at regular intervals, and handle connection errors. This experiment simulates data transmission from an IoT device to the IIOT platform, providing a comprehensive guide for beginners to get started.

Prerequisites

  • Node.js: Ensure that Node.js is installed on your machine. It can be downloaded from nodejs.org.
  • MQTT Broker Details: Acquire the hostname, port, username, and password for the MQTT broker from the IIOT platform.
  • Create a Project: Follow the instructions in this section to establish a new project.
  • Create an Asset: Refer to the relevant section to define and integrate an asset into your project.
  • Create a Parameter: Refer the relevant section to configure and set up parameters for your asset.

Step 1:

Install the MQTT Library

You need to install the necessary Node.js library (mqtt). The latest stable version can be found in the npm registry and can be installed using the following command:

npm install mqtt or yarn add mqtt

Step 2:

Retrieve MQTT Credentials

Log in to the IIOT Platform and navigate to the project tab. From there, you can retrieve your MQTT username and copy the token from the settings section, which serves as your MQTT password.

Fig 1: Settings Section

Additionally, you will need the MQTT topic, which can be found by navigating to the assets and parameters sections.

Fig 2: Retrive topic

Step 3:

Develop the script

Create a new file named iiot-mqtt-script.js and incorporate the following code. This script will establish a connection to the MQTT broker, publish sensor data, and handle any potential errors.

Program:

const mqtt = require("mqtt");

// Constants for your credentials and the MQTT topic
const USERNAME = ""; // username
const PASSWORD = ""; //password
const PUBLISH_TOPIC = ""; //topic

// Configure MQTT client
const client = mqtt.connect("mqtt://iiotif.com:1883", {
username: USERNAME,
password: PASSWORD,
clientId: `iotif_client_${Math.random().toString(16).slice(3)}`,
clean: true,
connectTimeout: 4000,
reconnectPeriod: 1000,
});

client.on("connect", () => {
console.log("Connected to MQTT broker");

// Subscribe for debugging
client.subscribe(PUBLISH_TOPIC, { qos: 1 }, (err) => {
if (err) {
console.error("Error subscribing to topic:", err);
} else {
console.log(`Subscribed to ${PUBLISH_TOPIC}`);
}
});

// Generate simulated data
const generateRandomData = () => {
const temperature = 15 + Math.random() * 15; // Range: 15–30
const humidity = 20 + Math.random() * 30; // Range: 20–50
return {
temperature: parseFloat(temperature.toFixed(2)),
humidity: parseFloat(humidity.toFixed(2)),
};
};

// Publish the message
const publishMessage = () => {
const message = generateRandomData();
message.timestamp = Date.now();
client.publish(
PUBLISH_TOPIC,
JSON.stringify(message),
{ qos: 1, retain: false },
() => {
console.log("Message published:", message);
}
);
};

// Publish every 5 seconds
setInterval(publishMessage, 5000);
});

// Debug incoming messages
client.on("message", (topic, message) => {
console.log(`Received message on ${topic}: ${message.toString()}`);
});

// Handle errors
client.on("error", (err) => {
console.error("Failed to connect to MQTT broker:", err);
});

// Handle disconnections
client.on("close", () => {
console.log("Disconnected from MQTT broker");
});

Explanation:

MQTT Client Configuration

  • Credentials: Replace USERNAME, PASSWORD, and PUBLISH_TOPIC with your actual MQTT credentials and topic.
  • Connection: The MQTT client connects to the broker at mqtt://iiotif.com:1883 using the provided credentials.
const client = mqtt.connect("mqtt://iiotif.com:1883", {
username: USERNAME,
password: PASSWORD,
clientId: `iotif_client_${Math.random().toString(16).slice(3)}`,
clean: true,
connectTimeout: 4000,
reconnectPeriod: 1000,
});

Data Generation

  • generateRandomData Function: Simulates sensor data with small variations. This function uses Math.sin and Math.cos to create minor fluctuations around base values for temperature and humidity.

  • The key used during parameter creation should be reused here as the value for the variable.

Fig 3: Retrive key

const generateRandomData = () => {
const temperature = 15 + Math.random() * 15; // 15–30
const humidity = 20 + Math.random() * 30; // 20–50
return {
temperature: parseFloat(temperature.toFixed(2)),
humidity: parseFloat(humidity.toFixed(2)),
};
};

Message Publishing

  • publishMessage Function: Publishes the generated sensor data to the specified topic every 5 seconds.
const publishMessage = () => {
const message = generateRandomData();
message.timestamp = Date.now();
client.publish(
PUBLISH_TOPIC,
JSON.stringify(message),
{ qos: 1, retain: false },
() => {
console.log("Message published:", message);
}
);
};

setInterval(publishMessage, 5000);
  • Publishing Interval: Set to 5 seconds using setInterval.
setInterval(publishMessage, 5000);

Error Handling

  • client.on("error"): Logs any connection errors to assist with troubleshooting.
client.on("message", (topic, message) => {
console.log(`Received message on ${topic}: ${message.toString()}`);
});

Step 4:

Executing the Script

  • Open a Terminal: Navigate to your project directory.
  • Execute the Script: Run the script using Node.js with the following command:
node iiot-mqtt-script.js

Step 5:

Monitor Data on the IIOT Platform

The console will indicate "Connected to MQTT broker" upon a successful connection. Additionally, every 5 seconds, the console will display the published message.

Fig 4: Graphical Data Representation

Troubleshooting

  • Connection Errors: Confirm that your MQTT broker details (host, port, username, password) are accurate.
  • Network Issues: Verify your network connection and check any firewall settings that might be blocking MQTT traffic.
  • Broker Availability: Ensure that the MQTT broker is available and operational.

Conclusion

This experiment illustrates how to use Node.js to interact with an IIOT platform via MQTT. The script establishes a connection to the broker, publishes sensor data, and manages potential errors. By following this guide, you can replicate and tailor the experiment to meet your specific requirements.

IIOT Platform Using Python

· 3 min read

In this tutorial, we'll demonstrate how to send random data to the IIOT Platform using Python scratch code and MQTT. This tutorial will enable the user to collect and analyse data from various sources and use it to make informed decisions. Overall, this tutorial provides a comprehensive guide for beginners to get started with the IIOT platform.

Step 1:

Download and Install Required Python Module

You need to download the required Python module (paho-mqtt). The latest stable version is available in the Python Package Index (PyPi) and can be installed using this command:

pip install paho-mqtt

Step 2:

Retrieve MQTT Credentials

Log in to the IIOT Platform and go to the project tab. From there, you can copy your MQTT username and token inside the setting section and your MQTT topic inside the assets section that is needed in the program.

Fig 1: Settings Section

Step 3:

Implement MQTT Connection and Data Publishing

Now, let's dive into the Python code that establishes the connection with IIOT Platform and send the random data on the platform.

Explanation:

Including the necessary modules: We include the required modules, such as Paho-mqtt, random and time.

Defining the constant: The code defines the credentials of MQTT details such as server, username, password, and topic.

Create necessary objects: The code creates an object called a client that handles the mqtt server and connects to it.

Connecting to the MQTT server: The client is responsible for connecting to the MQTT server and publishing the sensor data. It establishes a connection to the MQTT server using the provided credentials. It reads the random data and publishes it to the appropriate topic.

Publishing the data on the platform: We create a loop in which the random data is uploaded every 3 seconds. The random data (temperature and humidity) is sent in string format.

Programs:


import time
import random
import paho.mqtt.client as mqtt


mqtt_host = "iiotif.com" # Your server name
mqtt_username = "sampleProject_1683791983321" # Your MQTT username
mqtt_password = "EcLA8nzJ4izURJ0vPHNru_7UUm_T-08-" # your MQTT passwrod
mqtt_publish_topic = "a/sampleAsset_1683791983321" # The MQTT topic
mqtt_client_id = "IIOTPlatform_pico"


# Initialize our MQTTClient and connect to the MQTT server
client = mqtt.Client()
client.username_pw_set(mqtt_username, mqtt_password)
client.connect(mqtt_host, 1883)


try:
while True:
temperature = random.randint(25, 30)
humidity = random.randint(65, 70)
print("Humidity: {}% Temperature: {}°C".format(humidity, temperature))
temperature_str = "{:.2f}".format(temperature)
humidity_str = "{:.2f}".format(humidity)
payload = "{{\"temperature\":{},\"humidity\":{}}}".format(temperature_str, humidity_str)
client.publish(mqtt_publish_topic, str(payload))
time.sleep(3)
except Exception as e:
print(f'Failed to publish message: {e}')
finally:
client.disconnect()

Step 4:

Execute the Python Script

After inserting your MQTT credentials and MQTT topic in the code, Run the code on any Python software (in my case I am using VS code).

Step 5:

Monitor Data on the IIOT Platform

Allow the programme to run for a while so that you can view some useful data on the website. A sample set of readings stored on the website is shown below in graphical format and tabular data:

Fig 2: Graphical Data Representation

Conclusion

In this tutorial, we looked at how to use paho-mqtt to send random data to the IIOT Platform. By using paho-mqtt, we were able to establish a connection with the IIOT Platform and send random data in a structured format. With the knowledge gained from this tutorial, users can now confidently use paho-mqtt to send their own data to the IIOT Platform.

Publishing Data Using Python library

· 3 min read

In this tutorial, we'll demonstrate how to send random data to the IIOT Platform using Python scratch code and the IIOTPlatform library. By following this tutorial, you will be able to send random data to the IIOT Platform with ease and efficiency. The Python scratch code and IIOTPlatform library make the process straightforward and accessible. So, let's get started and begin sending random data to the IIOT Platform!

Step 1:

Download the IIOTPlatform Library

First, you need to download the IIOTPlatform library. For this, you can download this library using this link ( Download Library. )

Step 2:

Retrieve MQTT Credentials

Log in to the IIOT Platform and go to the project tab. From there, you can copy your MQTT username and token inside the setting section and your MQTT topic inside the assets section that is needed in the program.

Fig 1: Settings Section

Step 3:

Implement MQTT Connection and Data Publishing to IIOT Platform

Now, let's dive into the Python code that establishes the connection with the IIOT Platform and send the random data on the platform.

Explanation:

Including the necessary modules: We include the required modules, such as IIOTPlatform, random and time.

Defining the constant: The code defines the credentials of MQTT details such as server, username, password, and topic.

Create necessary objects: The code creates a variable called Object that handles the MQTT server.

Connecting to the MQTT server: The Object is responsible for connecting to the MQTT server and publishing the sensor data. It establishes a connection to the MQTT server using the provided credentials.

Publishing the data on the platform: We create a loop in which the random data is uploaded every 3 seconds. In this loop, the variable called Object reads the random data and publishes it to the appropriate topic. The random data (temperature and humidity) is sent in string format.

Programs:


import random
import time
from IOTPlatform_functions import IOTPlatform


mqtt_username = "sampleProject_1683791983321" # Your MQTT username
mqtt_password = "EcLA8nzJ4izURJ0vPHNru_7UUm_T-08-" # your MQTT passwrod
mqtt_publish_topic = "a/sampleAsset_1683791983321" # The MQTT topic


if __name__ == '__main__':
Object = IOTPlatform()
Object.debugMode(condition=True)
Object.setCredentials(mqtt_username, mqtt_password)
Object.setTopic(mqtt_publish_topic)
while True:
temperature = random.randint(25, 30)
humidity = random.randint(65, 70)
Object.addParameter("temperature", temperature)
Object.addParameter("humidity", humidity)
Object.publish()
time.sleep(3)

Step 4:

Execute the Python Script

After inserting your MQTT credentials and MQTT topic in the code, Run the code on any Python software (in my case I am using VS code).

Step 5:

Monitor Data on the IIOT Platform

Allow the programme to run for a while so that you can view some useful data on the website. A sample set of readings stored on the website is shown below in graphical format and tabular data:

Fig 2: Graphical Data Representation

Conclusion

In this tutorial, we looked at how to use the IIOTPlatform library to send random data to the IIOT Platform. By following the steps outlined in this tutorial, you should now have a basic understanding of how to use the IIOTPlatform library to send data to the IIOT Platform.

SI7021 with ESP32

· 4 min read

In this tutorial, we will see how to interface the Si7021 humidity and temperature sensor with the ESP32 board and send the data to the IIOT Platform. The Si7021 is a humidity and temperature sensor. The Si7021 I2C sensor has humidity and temperature sensor elements, an analogue-to-digital converter, signal processing, and calibration data. Here is a picture of the Si7021 humidity and temperature sensor and the ESP32 board.

Fig 1: SI7021 And ESP32

We will use the Witty Fox Storm Board with the IIOT Platform library to read the humidity and temperature readings and send them to the IIOT Platform.

Step 1:

Hardware Setup

The Si7021 Humidity and Temperature Sensor is directly compatible with the ESP32 Board through the I2C ports P9 and P10. These are the connections you need to make from the ESP32 board to Si7021:

ESP32 boardSi7021
3.3 VVCC
GNDGND
P9(SCL)SCL
P10(SDA)SDA

Fig 2: SI7021 With ESP32 Connections

Step 2:

Retrieve MQTT Credentials

Go to the project tab. From there, you can copy your MQTT username and token inside the setting section and your MQTT topic inside the assets section that is needed in the program.

Fig 3: Settings Section

Step 3:

Install Required Libraries

(downloading the libraries):

Connect your ESP32 board with the Si7021 humidity and temperature sensor. To send the sensor readings to the IIOT Platform, install the Adafruit Si7021 and PubSubClient libraries using the Library Manager in the Arduino IDE. Go to Sketch > Include Library > Manage Libraries and search for the library name in the library manager.

Fig 4: Arduino Library Manger

You can download IIOTPlatform library from HERE DOWNLOAD THE LIBRARY

Step 4:

Implement Arduino Sketch

First, you need to include the necessary libraries. Create an Adafruit si7021 object called sensor and an IIOTPlatform object called obj. Next, you have to set the network credentials in the initWiFi() section, the MQTT credentials in the setCredentials() section, and the MQTT topic in the setTopic() section for the ESP32 board. After that, we check whether the Si7021 module is working or not. In the loop function, we use the Adafruit sensor object to read the data from the si7021 sensor and send it to the IIOT Platform using the IIOTPlatform sensor object.

Program


#include "Adafruit_Si7021.h"
#include "IIOTPlatform.h"
IIOT obj;
Adafruit_Si7021 sensor = Adafruit_Si7021();
void setup() {
Serial.begin(115200);
obj.debugMode(true);
obj.initWifi("wifi_ssid", "WiFi_password");
obj.setCredentials("mqtt_username", "mqtt_password");
obj.initMqtt();
obj.setTopic("mqtt_topic");
while (!Serial) {
delay(10);
}
Serial.println("Si7021 test!");

if (!sensor.begin()) {
Serial.println("Did not find Si7021 sensor!");
while (true);
}
Serial.print("Found model ");
switch(sensor.getModel()) {
case SI_Engineering_Samples:
Serial.print("SI engineering samples"); break;
case SI_7013:
Serial.print("Si7013"); break;
case SI_7020:
Serial.print("Si7020"); break;
case SI_7021:
Serial.print("Si7021"); break;
case SI_UNKNOWN:
default:
Serial.print("Unknown");
}
Serial.print(" Rev(");
Serial.print(sensor.getRevision());
Serial.print(")");
Serial.print(" Serial #");
Serial.print(sensor.sernum_a, HEX);
Serial.println(sensor.sernum_b, HEX);
}

void loop () {
float temperature = sensor.readTemperature();
float humidity = sensor.readHumidity();
obj.addParameter("temperature", temperature);
obj.addParameter("humidity", humidity);
obj.publish();
Serial.print("Humidity: ");
Serial.print(sensor.readHumidity(), 2);
Serial.print(" Temperature: ");
Serial.println(sensor.readTemperature(), 2);
delay(1000);
}

Step 5:

Upload Code to ESP32 Board

After inserting your network credentials, MQTT credentials, and MQTT topic in the code, upload the code to your ESP32 board.

Step 6:

Monitor Data on IIOT Platform

Allow the programme to run for a while so that you can view some useful data on the website. A sample set of readings stored on the website is shown below in graphical format:

Fig 5: Graphical Data Representation

OPT3001 with ESP32

· 4 min read

In this tutorial, we'll demonstrate how to connect the OPT3001 ambient light sensor to the ESP32 board and transmit data to the IIOT platform. The OPT3001 is a single-chip lux metre that measures the intensity of light. The OPT3001 is designed for systems that create light-based experiences for humans and is an ideal replacement for photodiodes, photoresistors, or other ambient light sensors. Here is a picture of the OPT3001 ambient light sensor and the ESP32 board.

Fig 1: OPT3001 And ESP32

Step 1:

Hardware Setup

The OPT30001 Ambient Light Sensor is directly compatible with the ESP32 Board via I2C ports P9 and P10. These are the connections you need to make from the ESP32 board -> OPT3001:

ESP32 boardOPT3001
3.3 VVCC
GNDGND
P9(SCL)SCL
P10(SDA)SDA

Fig 2: OPT3001 And ESP32 Connections

Step 2:

Retrieve MQTT Credentials

Go to the project tab. From there, you can copy your MQTT username and token inside the setting section and your MQTT topic inside the assets section that is needed in the program.

Fig 3: Settings Section

Step 3:

Install Required Libraries

(Downloading the libraries):

Connect your ESP32 board with OPT3001 Sensor. To send the sensor readings to the IIOT Platform, install the ClosedCube OPT3001 and PubSubClient libraries using the Library Manager in the Arduino IDE. Go to Sketch > Include Library > Manage Librariesand search for the library name in the library manager.

Fig 4: Arduino Library Manger

You can download IIOT_Platform_ESP32 library from HERE. [DOWNLOAD THE LIBRARY]

Step 4:

Implement Arduino Sketch

First, you need to include all the liberties. The Wire.h library uses the I2C communication protocol, the ClosedCube_OPT3001.h library reads from the sensor, and the IIOTPlateform.h library sends the data to the IIOT platform. Then, create a ClosedCube_OPT3001 object called opt3001 and an IIOTPlatform object called obj. Next, you have to set the network credentials in the initWiFi() section, the MQTT credentials in the setCredentials() section, and the MQTT topic in the setTopic() section for the ESP32 board. Next, there are two main functions: configureSensor() and printResult(). The first function is used to initialise and calibrate the sensor, and the second is used to get the output, whether it gets the data or not. In the loop function, we get the data using the printResult() function; after that, we store the data in a variable and send this data to the IIOT Platform using the addParameter() and publish() functions.

Program

#include <Wire.h>
#include <ClosedCube_OPT3001.h>
#include "IIOTPlatform.h"

IIOT obj;
ClosedCube_OPT3001 opt3001;
#define OPT3001_ADDRESS 0x44
void setup()
{
Serial.begin(115200);
obj.debugMode(true);
obj.initWifi("wifi_ssid", "WiFi_password");
obj.setCredentials("mqtt_username", "mqtt_password");
obj.initMqtt();
obj.setTopic("mqtt_topic");
opt3001.begin(OPT3001_ADDRESS);
Serial.println("ClosedCube OPT3001 Arduino Test");
Serial.print("OPT3001 Manufacturer ID");
Serial.println(opt3001.readManufacturerID());
Serial.print("OPT3001 Device ID");
Serial.println(opt3001.readDeviceID());
configureSensor();
printResult("High-Limit", opt3001.readHighLimit());
printResult("Low-Limit", opt3001.readLowLimit());
Serial.println("----");
}
void configureSensor()
{
OPT3001_Config newConfig;
newConfig.RangeNumber = B1100;
newConfig.ConvertionTime = B0;
newConfig.Latch = B1;
newConfig.ModeOfConversionOperation = B11;
OPT3001_ErrorCode errorConfig = opt3001.writeConfig(newConfig);
if (errorConfig != NO_ERROR)
printError("OPT3001 configuration", errorConfig);
else {
OPT3001_Config sensorConfig = opt3001.readConfig();
Serial.println("OPT3001 Current Config:");
Serial.println("------------------------------");
Serial.print("Conversion ready (R):");
Serial.println(sensorConfig.ConversionReady,HEX);
Serial.print("Conversion time (R/W):");
Serial.println(sensorConfig.ConvertionTime, HEX);
Serial.print("Fault count field (R/W):");
Serial.println(sensorConfig.FaultCount, HEX);
Serial.print("Flag high field (R-only):");
Serial.println(sensorConfig.FlagHigh, HEX);
Serial.print("Flag low field (R-only):");
Serial.println(sensorConfig.FlagLow, HEX);
Serial.print("Latch field (R/W):");
Serial.println(sensorConfig.Latch, HEX);
Serial.print("Mask exponent field (R/W):");
Serial.println(sensorConfig.MaskExponent, HEX);
Serial.print("Mode of conversion operation (R/W):");
Serial.println(sensorConfig.ModeOfConversionOperation, HEX);
Serial.print("Polarity field (R/W):");
Serial.println(sensorConfig.Polarity, HEX);
Serial.print("Overflow flag (R-only):");
Serial.println(sensorConfig.OverflowFlag, HEX);
Serial.print("Range number (R/W):");
Serial.println(sensorConfig.RangeNumber, HEX);
Serial.println("------------------------------");
}
}
void printResult(String text, OPT3001 result) {
if (result.error == NO_ERROR) {
Serial.print(text);
Serial.print(": ");
Serial.print(result.lux);
Serial.println(" lux");
}
else {
printError(text,result.error);
}
}
void printError(String text, OPT3001_ErrorCode error) {
Serial.print(text);
Serial.print(": [ERROR] Code #");
Serial.println(error);
}
void loop()
{
OPT3001 result = opt3001.readResult();
printResult("OPT3001", result);

float opt3001 = result.lux;
obj.addParameter("opt3001", opt3001);
obj.publish();
delay(1000);
}

Step 5:

Upload Code to ESP32 Board

After inserting your network credentials, MQTT credentials and MQTT topic in the code, upload the code to your ESP32 board.

Step 6:

Monitor Data on IIOT Platform

Allow the programme to run for a while so that you can view some useful data on the website. A sample set of readings stored on the website is shown below in graphical format and tabular data:

Fig 5: Graphical Data Representation

Fig 6: Tabular Data Representation

Conclusion

In this tutorial, we looked at utilising an ESP32 board and an OPT3001 ambient light sensor to send data from an OPT3001 sensor.

Arduino Uno with Ethernet Shield

· 6 min read

In this tutorial, we will explore how to use an Arduino board along with the Ethernet shield to send sensor data from a DHT sensor to the IIOT Platform. The DHT22 can measure temperatures from -40°C to +125°C with an accuracy of 0.5°C and relative humidity from 0 to 100% with an accuracy of 2–5%. Here is a picture of the DHT22 sensor, Ethernet shield, and Arduino UNO.

Fig 1: DHT22, Ethernet Shield and Arduino UNO

Step 1:

Hardware Setup

First, you need to connect the Ethernet shield to the Arduino UNO board, and then connect the DHT sensor to your board by following the appropriate pin connections. Connections are relatively simple. Begin by connecting the + (VCC) pin to the Arduino’s 5V output and the – (GND) pin to ground. Finally, connect the Out pin to digital pin #5.

Step 2:

Retrieve MQTT Credentials

Go to the project tab. From there, you can copy your MQTT username and token inside the setting section and your MQTT topic inside the assets section that is needed in the program.

Fig 2: Settings Section

Step 3:

Connect Ethernet Shield to Internet

Connect the Ethernet shield with the Internet: You need to connect the Ethernet shield to your router or your computer via an Ethernet cable (RJ45 cable). If you want to connect the Ethernet shield to your router, then go HERE.

The first step is to enable sharing on your existing internet. In my case, the laptop is connected to the router over Wi-Fi. Open Control Panel, then Network & Internet, then Network & Sharing Center. Click on the existing internet connection.

Fig 3: Windows Network and Sharing Center

On the next screen, click PROPERTIES and then SHARING.

Fig 4: Wireless Network Connection Properties

Tick the box to enable Internet connection sharing.

Fig 5: Internet Connection Sharing

Now plug in the USB cable to the Arduino, and then connect the RJ45 straight cable from the shield to the RJ45 port of the laptop.

Fig 6: Hardware Setup

As soon as you connect the RJ45 cable, you can see an unidentified network.

Fig 7: Windows Network and Sharing Center

Click on that new network and select properties. On the next screen, double-click on Internet Protocol Version 4 (TCP/IPV4).

Fig 8: Local Area Connection Properties

You can see an IP address like 192.168.137.1. Note that this is the new gateway IP of the new network formed by the Ethernet shield. If you do not see any IP, just select “Use the following IP” and manually enter the IP.

Fig 9: IPV4 Properties

Now run RUN > CMD > IPCONFIG /ALL to verify the IP. Under the Ethernet adapter, the gateway IP of the new network is displayed. Note that this is the gateway IP, and the Ethernet shield will be allotted IP in this range.

Fig 10: Windows CMD

Now, we can use this Ethernet shield to send the sensor data to the IIOT platform or the server.

Step 4:

Library Installation

Library Installation:Install the Ethernet, PubSubClient and DHT sensor library on your Arduino IDE. This library will enable us to connect to the IIOT Platform and publish the sensor data. Go to Sketch > Include Library > Manage Libraries and search for the library name in the library manager and install the library.

Fig 11: Arduino Library Manger

Step 5:

Setting Up the Code

Setting up the code Now, the code will be divided into different sections:

Including the necessary libraries and defining constants: We include the required libraries, such as Ethernet, PubSubClient, and DHT. Additionally, we define constants like MQTT server details, the Ethernet Mac ID, and DHT sensor details.

Connecting to the MQTT server: We connect to the IIOT Platform, set up the client, and define the objects. We also put in the MQTT username and password.

Reading the DHT sensor data: We define a function called readDHTSensor() that reads the temperature and humidity values from the DHT sensor. If the readings are successful, we proceed to publish the data using the function publishSensorData().

Publishing sensor data to the IIOT Platform: We format the temperature and humidity data into a JSON payload and publish it to the IIOT Platform.

Program


#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>

#define DHT_PIN 5
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
byte mac[] = {0xD4, 0xA8, 0xE2, 0xFE, 0xA0, 0xA1};
char server[] = "www.iiotif.com";
void callback(char* topic, byte* payload, unsigned int length) {
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Ethernet.begin(mac);
Serial.begin(9600);
dht.begin();
client.setServer(server, 1883);
client.setCallback(callback);
while (!client.connected()) {
Serial.print("Connecting to MQTT server...");
if(client.connect("arduinoClient","ethernetshield_1685692281114", "cICJJrLVia6YYwnbjcCQi6nhIyqi_ayT")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
}

void readDHTSensor() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(temperature);
Serial.println("°C");
publishSensorData(temperature, humidity);
}
void loop()
{
client.loop();
readDHTSensor();
delay(5000);
}
void publishSensorData(float temperature, float humidity) {
char temperatureStr[6];
char humidityStr[6];
dtostrf(temperature, 4, 2, temperatureStr);
dtostrf(humidity, 4, 2, humidityStr);
char payload[50];
snprintf(payload, sizeof(payload), "{"temperature":%s,"humidity":%s}", temperatureStr, humidityStr);
client.publish("a/weather condition_1685692307330", payload);
}

Step 6:

Monitor MQTT Connection and Sensor Data

After uploading the code to the Arduino board, open the serial monitor to observe the connection process. You should see messages indicating the MQTT server connection status. If everything goes smoothly, the DHT sensor data will be published to the specified MQTT topic.

Step 7:

Monitor Data on IIOT Platform

Allow the program to run for a while so that you can view some useful data on the website. A sample set of readings stored on the website is shown below in graphical format:

Fig 12: Graphical Data Representation

Conclusion

In this tutorial, we explored the process of sending DHT sensor data to the IIOT Platform using an Arduino board, an Ethernet shield, and the PubSubClient library.