๐Ÿ”Œ

Arduino + MQTT

๐Ÿ‘จโ€๐Ÿณ Chefโฑ๏ธ 60 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขNone - we start from scratch

What you'll build

A temperature and humidity sensor connected to the internet that sends data to your computer every 5 seconds.

When finished you'll have:

  • An ESP32 reading real temperature and humidity from your room
  • Data traveling over WiFi to a public MQTT broker
  • A script on your computer showing real-time data

This is your first real IoT project. Hardware + Software + Internet.


Shopping list (exact)

You need these specific components:

ComponentExact modelApprox priceWhere to buy
MicrocontrollerESP32 DevKit V1 (30 pins)$5-8 USDAmazon, AliExpress
SensorDHT22 (blue) or DHT11 (cheaper blue)$2-5 USDAmazon, AliExpress
CablesJumper wires female-female (3 cables)$2 USDAny electronics store
USB CableMicro USB (to program ESP32)$2 USDYou probably have one

Total: ~$12-15 USD

Note: DHT22 is more accurate than DHT11. If you can, buy the DHT22.


Wiring diagram

Connect the DHT22 sensor to the ESP32 like this:

    ESP32 DevKit V1                    DHT22
    +--------------+                  +-------+
    |              |                  |       |
    |         3.3V |------ wire ------| VCC   |  (pin 1 - left)
    |              |                  |       |
    |        GPIO4 |------ wire ------| DATA  |  (pin 2)
    |              |                  |       |
    |          GND |------ wire ------| GND   |  (pin 4 - right)
    |              |                  |       |
    +--------------+                  +-------+

    Note: DHT22 pin 3 is not used (leave disconnected)

Connection table:

ESP32 PinWireDHT22 PinDescription
3.3VRedPin 1 (VCC)Sensor power
GPIO4YellowPin 2 (DATA)Sensor data
GNDBlackPin 4 (GND)Ground

Important: Use 3.3V, NOT 5V. The ESP32 works at 3.3V.


Step 1: Install Arduino IDE

  1. Go to arduino.cc/en/software
  2. Download Arduino IDE 2.x for your operating system
  3. Install and open Arduino IDE

Step 2: Configure ESP32 in Arduino IDE

ESP32 doesn't come pre-installed. We need to add it:

  1. Open Arduino IDE
  2. Go to File โ†’ Preferences (or Arduino IDE โ†’ Settings on Mac)
  3. In "Additional boards manager URLs" add:
    https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
    
  4. Click OK
  5. Go to Tools โ†’ Board โ†’ Boards Manager
  6. Search "esp32"
  7. Install "esp32 by Espressif Systems" (takes 2-3 minutes)

Step 3: Install libraries

You need 2 libraries:

  1. Go to Tools โ†’ Manage Libraries
  2. Search "DHT sensor library" by Adafruit โ†’ Install
  3. Search "PubSubClient" by Nick O'Leary โ†’ Install

If asked about dependencies, accept to install them.


Step 4: Connect the ESP32

  1. Connect ESP32 to your computer with USB cable
  2. Go to Tools โ†’ Board and select "ESP32 Dev Module"
  3. Go to Tools โ†’ Port and select the port (COM3, COM4 on Windows, or /dev/cu.usbserial on Mac)

Port not showing? You need the CP210x driver:


Step 5: The complete code

Create a new sketch and paste this code:

// ============================================
// IoT Sensor: ESP32 + DHT22 + MQTT
// luxIA.us - Complete tutorial
// ============================================

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

// --- CONFIGURATION: EDIT THESE VALUES ---
const char* WIFI_SSID = "YOUR_WIFI_NAME";      // Your WiFi name
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";  // Your WiFi password
const char* MQTT_SERVER = "broker.hivemq.com"; // Public MQTT broker (free)
const int MQTT_PORT = 1883;
const char* MQTT_TOPIC = "luxia/sensor/yourName"; // Change "yourName" to something unique
// ----------------------------------------

// Sensor configuration
#define DHT_PIN 4        // GPIO4 - where you connected DATA
#define DHT_TYPE DHT22   // Change to DHT11 if using that model

DHT dht(DHT_PIN, DHT_TYPE);
WiFiClient espClient;
PubSubClient mqtt(espClient);

void setup() {
  // Start serial monitor (to see messages on your computer)
  Serial.begin(115200);
  Serial.println();
  Serial.println("=== IoT Sensor starting ===");

  // Start sensor
  dht.begin();
  Serial.println("DHT sensor started");

  // Connect WiFi
  Serial.print("Connecting to WiFi: ");
  Serial.println(WIFI_SSID);
  WiFi.begin(WIFI_SSID, WIFI_PASS);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.print("WiFi connected! IP: ");
  Serial.println(WiFi.localIP());

  // Configure MQTT
  mqtt.setServer(MQTT_SERVER, MQTT_PORT);
  Serial.println("MQTT configured");
}

void connectMQTT() {
  while (!mqtt.connected()) {
    Serial.print("Connecting to MQTT...");

    // Create unique ID for this device
    String clientId = "ESP32-" + String(random(0xffff), HEX);

    if (mqtt.connect(clientId.c_str())) {
      Serial.println(" connected!");
    } else {
      Serial.print(" failed, code: ");
      Serial.print(mqtt.state());
      Serial.println(" - retrying in 5 seconds");
      delay(5000);
    }
  }
}

void loop() {
  // Ensure MQTT connection
  if (!mqtt.connected()) {
    connectMQTT();
  }
  mqtt.loop();

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

  // Check valid reading
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Error reading sensor!");
    delay(2000);
    return;
  }

  // Create JSON message
  String message = "{\"temp\":" + String(temperature, 1) +
                   ",\"hum\":" + String(humidity, 1) + "}";

  // Send via MQTT
  mqtt.publish(MQTT_TOPIC, message.c_str());

  // Show in Serial Monitor
  Serial.print("Sent: ");
  Serial.println(message);

  // Wait 5 seconds
  delay(5000);
}

Step 6: Configure YOUR WiFi

In the code, change these lines with your data:

const char* WIFI_SSID = "YOUR_WIFI_NAME";      // Your WiFi network name
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";  // Your WiFi password
const char* MQTT_TOPIC = "luxia/sensor/yourName"; // Change yourName

Step 7: Upload the code

  1. Click the Upload button (right arrow) in Arduino IDE
  2. Wait for compilation (30-60 seconds)
  3. Wait for upload to ESP32 (shows "Connecting..." then percentages)
  4. When done, open Tools โ†’ Serial Monitor
  5. Select 115200 baud in the bottom right corner

Step 8: Verify it works

In Serial Monitor you should see:

=== IoT Sensor starting ===
DHT sensor started
Connecting to WiFi: YOUR_WIFI
....
WiFi connected! IP: 192.168.1.105
MQTT configured
Connecting to MQTT... connected!
Sent: {"temp":23.5,"hum":45.2}
Sent: {"temp":23.6,"hum":45.1}
Sent: {"temp":23.5,"hum":45.3}

If you see this, it works! Your sensor is sending data to the internet.


Step 9: View data from your computer

Now let's receive that data on your computer.

Install an MQTT client:

npm install -g mqtt

Subscribe to your topic:

mqtt sub -h broker.hivemq.com -t "luxia/sensor/yourName"

You should see data arriving:

{"temp":23.5,"hum":45.2}
{"temp":23.6,"hum":45.1}

Troubleshooting

ProblemSolution
COM port not showingInstall CP210x driver (link above)
"Error reading sensor"Check wires: 3.3V to VCC, GPIO4 to DATA, GND to GND
Won't connect to WiFiVerify exact name and password (case-sensitive)
Won't connect to MQTTCheck internet connection, try restarting ESP32
Wrong temperatureWait 2 minutes for sensor to stabilize

Next step

โ†’ Analytics Dashboard - Display this data in charts