Skip to content

Wokwi Virtual IoT Lab

This lab needs only a laptop and a browser. You will simulate an ESP32 with a DHT22 temperature/humidity sensor and a relay in Wokwi, publish JSON telemetry to an MQTT broker, and switch the relay by sending commands from MQTTX.

+---------------------- Wokwi (browser) ----------------------+
| DHT22 --> ESP32 (Arduino sketch) --> relay module (LED) |
+------------------------------+------------------------------+
| Wi-Fi "Wokwi-GUEST"
v
public MQTT broker (TCP 1883)
^
| subscribe / publish
MQTTX on laptop

Topics (replace PREFIX with your own random string, for example iotinfo-k7x2q9m4):

Topic Direction Payload
PREFIX/telemetry ESP32 to broker {"temp":24.5,"hum":51.2,"relay":false}
PREFIX/cmd/relay MQTTX to ESP32 ON, OFF or TOGGLE
PREFIX/status ESP32 to broker online / offline (Last Will)
  1. Open wokwi.com, start a new ESP32 project (Arduino framework).
  2. Add parts with the blue + button: DHT22 and Relay Module. A small LED and a resistor help show the relay’s effect.
  3. Open the Library Manager (the library tab in the editor) and add:
Library (Library Manager name) Purpose
PubSubClient MQTT client
DHT sensor library (Adafruit) DHT22 driver
Adafruit Unified Sensor dependency of the DHT library

Wire in the Wokwi diagram editor (or edit diagram.json; the editor generates valid JSON for you, so use the GUI). Pin labels on parts may differ slightly by version, so match by function.

From To Note
DHT22 VCC ESP32 3V3 Wokwi allows 3.3 V; real DHT22 works from 3.3 to 5 V
DHT22 SDA (data) ESP32 GPIO4 Sketch below uses GPIO4
DHT22 GND ESP32 GND
Relay VCC ESP32 5V (VIN)
Relay GND ESP32 GND
Relay IN ESP32 GPIO26 Sketch below uses GPIO26
Relay COM to LED path optional Connect COM to 3V3/5V rail, NO through a resistor (about 220 ohm) to the LED anode, LED cathode to GND

Paste into sketch.ino. Change PREFIX first. Use a broker hostname of your choice.

#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
// ---- Settings you must change ----
const char* PREFIX = "iotinfo-CHANGE-ME-8chars"; // random, unique
const char* MQTT_HOST = "broker.hivemq.com"; // public, unauthenticated
const uint16_t MQTT_PORT = 1883;
// ---- Pins ----
#define DHT_PIN 4
#define DHT_TYPE DHT22
#define RELAY_PIN 26
const bool ACTIVE_LOW = false; // set true for active-low modules
DHT dht(DHT_PIN, DHT_TYPE);
WiFiClient wifiClient;
PubSubClient mqtt(wifiClient);
String tTelemetry, tCmd, tStatus;
bool relayOn = false;
unsigned long lastPublish = 0;
const unsigned long PUBLISH_MS = 5000;
void relayWrite(bool on) {
relayOn = on;
digitalWrite(RELAY_PIN, (on ^ ACTIVE_LOW) ? HIGH : LOW);
}
void onMessage(char* topic, byte* payload, unsigned int len) {
String msg;
for (unsigned int i = 0; i < len; i++) msg += (char)payload[i];
msg.trim();
msg.toUpperCase();
Serial.printf("CMD %s: %s\n", topic, msg.c_str());
if (msg == "ON") relayWrite(true);
else if (msg == "OFF") relayWrite(false);
else if (msg == "TOGGLE") relayWrite(!relayOn);
}
void connectWifi() {
Serial.print("WiFi");
WiFi.begin("Wokwi-GUEST", "", 6); // Wokwi's simulated open network
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
Serial.println(" connected");
}
void connectMqtt() {
while (!mqtt.connected()) {
String clientId = String(PREFIX) + "-" + String((uint32_t)esp_random(), HEX);
Serial.print("MQTT connecting... ");
// Last Will: broker publishes "offline" (retained) if we vanish
if (mqtt.connect(clientId.c_str(), nullptr, nullptr,
tStatus.c_str(), 0, true, "offline")) {
Serial.println("ok");
mqtt.publish(tStatus.c_str(), "online", true);
mqtt.subscribe(tCmd.c_str());
} else {
Serial.printf("failed rc=%d, retry in 3 s\n", mqtt.state());
delay(3000);
}
}
}
void setup() {
Serial.begin(115200);
digitalWrite(RELAY_PIN, ACTIVE_LOW ? HIGH : LOW); // start OFF
pinMode(RELAY_PIN, OUTPUT);
dht.begin();
tTelemetry = String(PREFIX) + "/telemetry";
tCmd = String(PREFIX) + "/cmd/relay";
tStatus = String(PREFIX) + "/status";
connectWifi();
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(onMessage);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) connectWifi();
if (!mqtt.connected()) connectMqtt();
mqtt.loop();
unsigned long now = millis();
if (now - lastPublish >= PUBLISH_MS) {
lastPublish = now;
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("DHT read failed");
return;
}
char buf[96];
snprintf(buf, sizeof(buf),
"{\"temp\":%.1f,\"hum\":%.1f,\"relay\":%s}",
t, h, relayOn ? "true" : "false");
mqtt.publish(tTelemetry.c_str(), buf);
Serial.println(buf);
}
}

Notes on the code:

  • WiFi.begin("Wokwi-GUEST", "", 6) is the documented way to join Wokwi’s simulated network; the channel argument speeds up connection.
  • The default PubSubClient packet limit is small (256 bytes); our payload is well under it.
  • The retained status topic plus Last Will lets a dashboard see whether the device is alive.
  1. Press the green Start button. In the serial monitor you should see WiFi... connected, MQTT connecting... ok, then a JSON line every 5 seconds.
  2. Click the DHT22 in the simulator and change temperature/humidity; the next reading should change.
  3. Open MQTTX, create a connection to the same host and port 1883 (no username/password), and subscribe to PREFIX/#. You should see telemetry messages and a retained status of online.
  4. In MQTTX publish ON to PREFIX/cmd/relay. The relay in Wokwi should click, and the next telemetry shows "relay":true.
  5. Publish OFF and TOGGLE to test the other commands.
Symptom Likely cause
Stuck on WiFi.... Typo in the SSID; it must be exactly Wokwi-GUEST with an empty password
rc=-2 on MQTT connect Broker unreachable or blocked; try another public broker host
No messages in MQTTX Prefix mismatch (case-sensitive) or different broker host
DHT read failed Data pin wired to the wrong GPIO, or wrong sensor type
Relay inverted Flip ACTIVE_LOW
You see strangers’ messages You subscribed to #; use your own prefix and never subscribe to # on a public broker

You can validate topic filters before testing with the MQTT Topic Tester. When you are ready for a physical build, go to wiring safety and the India BOM guide. More tools are in Tools.