Tuesday, February 4, 2025
How ToInternet of ThingsTutorials/DIY

How to Simulate an IoT Project on Wokwi with MQTT and ESP32

IoT (Internet of Things) projects often involve sending data between devices and cloud platforms. With Wokwi, you can simulate IoT projects, including MQTT communication, without physical hardware. This guide explains how to simulate an IoT project using MQTT and ESP32 in Wokwi, where sensor data is sent to an MQTT broker and displayed in real-time.

What You’ll Need

Components (Virtual in Wokwi):

  1. ESP32: The microcontroller for Wi-Fi and MQTT communication.
  2. DHT22 Sensor: Simulates temperature and humidity readings.
  3. Connecting Wires: For virtual connections between components.

Software:

  1. Wokwi: The platform for circuit simulation.
  2. MQTT Broker: You can use a free broker like Eclipse Mosquitto or HiveMQ.
  3. Arduino IDE: For coding the ESP32.

Step 1: Setting Up Your Wokwi Project

1.1: Start a New Project

  1. Visit Wokwi’s website and log in.
  2. Create a new project and select ESP32 as the microcontroller.

1.2: Add Components

  1. Open the Parts Library in Wokwi.
  2. Drag and drop the following components:
    • ESP32
    • DHT22 sensor
  3. Arrange the components for clarity.

Step 2: Wiring the Components

2.1: Connect the DHT22 Sensor

  • VCC: Connect to the 3.3V pin of the ESP32.
  • GND: Connect to the GND pin of the ESP32.
  • DATA: Connect to GPIO 15 of the ESP32.

Step 3: Writing the Code

3.1: Install Required Libraries

Ensure the following libraries are installed in the Arduino IDE:

  • PubSubClient: For MQTT communication.
  • DHT Sensor Library: For reading the DHT22 sensor.

3.2: Open the Code Editor

Write the following code to send sensor data to an MQTT broker:

#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

// Wi-Fi credentials
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";

// MQTT Broker details
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* mqtt_topic = "wokwi/weather";

// DHT Sensor settings
#define DHTPIN 15
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);

  // Initialize DHT sensor
  dht.begin();

  // Connect to Wi-Fi
  Serial.print("Connecting to Wi-Fi");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println(" Connected!");

  // Set MQTT server
  client.setServer(mqtt_server, mqtt_port);

  // Connect to MQTT broker
  connectToMQTT();
}

void connectToMQTT() {
  while (!client.connected()) {
    Serial.print("Connecting to MQTT...");
    if (client.connect("ESP32Client")) {
      Serial.println(" connected!");
    } else {
      Serial.print(" failed, rc=");
      Serial.print(client.state());
      Serial.println(" retrying in 5 seconds...");
      delay(5000);
    }
  }
}

void loop() {
  // Ensure MQTT connection
  if (!client.connected()) {
    connectToMQTT();
  }
  client.loop();

  // Read sensor data
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  // Check if readings are valid
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Print data to Serial Monitor
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" °C");
  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  // Publish data to MQTT topic
  String payload = "{\"temperature\": " + String(temperature) + ", \"humidity\": " + String(humidity) + "}";
  client.publish(mqtt_topic, payload.c_str());

  delay(2000); // Wait 2 seconds before the next reading
}

3.3: Configure Wi-Fi and Broker Details

  1. Replace Your_SSID and Your_PASSWORD with your Wi-Fi credentials.
  2. Use the broker details of your choice (e.g., HiveMQ or Mosquitto).

3.4: Run the Simulation

  1. Save your code in Wokwi.
  2. Click the Play button to start the simulation.
  3. Monitor the Serial output for connection and sensor updates.

Step 4: Monitoring MQTT Messages

  1. Use an MQTT client like MQTT Explorer or HiveMQ Web Client to monitor messages.
  2. Subscribe to the topic wokwi/weather.
  3. Verify that temperature and humidity data are published every 2 seconds.

Step 5: Enhancements and Next Steps

5.1: Add More Sensors

  • Include additional sensors like BMP280 for pressure or LDR for light intensity.
  • Publish all sensor data to separate MQTT topics.

5.2: IoT Dashboard Integration

  • Use platforms like ThingsBoard or Node-RED to create a dashboard.
  • Visualize sensor data in graphs and charts.

5.3: Control Devices

  • Simulate an IoT-enabled device (e.g., turning on a virtual LED based on MQTT commands).

Conclusion

Simulating an IoT project with MQTT and ESP32 on Wokwi is a powerful way to prototype and test your ideas. By combining sensor data, MQTT communication, and cloud tools, you can build and refine your IoT applications virtually. Experiment with advanced features to create robust and scalable IoT systems!

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

Harshvardhan Mishra has 753 posts and counting. See all posts by Harshvardhan Mishra

Leave a Reply

Your email address will not be published. Required fields are marked *