Basics · 10 min read

MQTT vs HTTP vs WebSocket: Differences, Latency and ESP32 Code

MQTT vs HTTP and WebSocket: request-response vs publish-subscribe, payload byte by byte, latency and battery math, ESP32 and Pico W code, which one to pick.

MQTT vs HTTP in one sentence: with HTTP the device sends a request to the server every time and waits for a response; with MQTT the device keeps a connection open to a middleman server (the broker) and publishes messages to topics, and everyone subscribed to that topic gets the message instantly. WebSocket sits between the two: it starts with an HTTP request and then turns into a two-way, always-open channel, which makes it ideal for live dashboards in the browser.

When you build an IoT project with an ESP32 or a Raspberry Pi Pico W, this choice directly decides battery life, latency and how complex your code gets. In this article you'll compare the three methods by model, payload, latency and battery use with real numbers, write three short ESP32 sketches and one Pico W script that send the same LDR light reading via HTTP, MQTT and WebSocket, and finally go through the most common wrong choices.

ESP32 development board sending data with HTTP, MQTT and WebSocket
The ESP32's built-in Wi-Fi supports all three methods without extra modules; the difference is in your code and the library you use.

What are HTTP, MQTT and WebSocket?

HTTP is the request-response protocol that carries web pages. The client (the ESP32) opens a TCP connection, sends a GET or POST request with its headers, the server returns a status code (e.g. 200) and a body, and then the connection is usually closed. It's the easiest method to set up, and most ready-made services such as ThingSpeak, Google Sheets and weather APIs speak HTTP. Its weak point is that the server can't push anything to the device on its own: to receive commands, the device has to keep asking (polling).

MQTT is a lightweight publish-subscribe protocol designed for low bandwidth and unreliable networks. In the middle sits a broker (e.g. Mosquitto). Devices connect to the broker once and keep the connection open; a sensor publishes a value to the home/livingroom/temperature topic, and the phone app, Node-RED or Home Assistant subscribed to that topic receives it immediately. The sender and the receiver don't need to know each other. The standard port is 1883, or 8883 with TLS.

WebSocket creates a two-way, always-open channel between a browser and a server. The connection starts as a normal HTTP request and switches protocol with an Upgrade header (101 Switching Protocols); after that, either side can send small frames whenever it wants. Because browsers support WebSocket natively, it's the most natural choice for a live dashboard running on an ESP32. It uses ws:// and encrypted wss:// addresses, usually on ports 80 and 443.

FeatureHTTPMQTTWebSocket
ModelRequest-responsePublish-subscribe (via a broker)Two-way, persistent channel
ConnectionUsually new for every requestPersistent TCPPersistent TCP
Server-to-device messagesNone (device must ask)Yes, instantlyYes, instantly
Overhead for a small valueHundreds of bytes of headersAbout 2–5 bytes + topic name2–14 byte frame header
Delivery guaranteeTCP + application retriesQoS levels 0, 1, 2None, the application handles it
Server in the middleWeb server or cloud APIBroker requiredWebSocket server (can be the ESP32)
Browser supportYesOnly via MQTT over WebSocketNative
Typical useInfrequent data, ready-made cloud servicesMulti-device home automation, telemetryLive web dashboard, game controller

Request-response vs publish-subscribe

In the request-response model the client always starts the conversation. That's great for a sensor sending data, but inefficient in the other direction. Imagine you want to switch a relay from your phone: with HTTP the ESP32 has to ask the server "any new command?" every second; that's 86,400 requests a day, and most of them get "no" as the answer. If you ask less often, the command runs late. In the publish-subscribe model the ESP32 subscribes to a topic and waits quietly; the moment you press the button, the broker pushes the message down the open connection and the relay switches within milliseconds. To keep the connection alive, only a 2-byte PINGREQ packet is sent when the keep-alive interval expires.

  • Broker: The server that receives messages and distributes them to subscribers. At home you use Mosquitto; in the cloud, services such as HiveMQ or EMQX.
  • Topic: A slash-separated address, e.g. bluegrays/salon/isik. + matches one level and # matches all levels below: bluegrays/# listens to everything in the house.
  • QoS: 0 at most once (no acknowledgement), 1 at least once (acknowledged with PUBACK, may arrive twice), 2 exactly once (four-step handshake). QoS 0 is usually enough for sensor data.
  • Retained message: The broker stores the last message on a topic; a newly connected subscriber gets the latest value without waiting.
  • Last Will (LWT): Left by the device when it connects; if the connection drops unexpectedly, the broker publishes this message (e.g. offline).
  • Keep-alive: If no packet is sent within the set time, the client sends a PINGREQ; if the broker hears nothing for 1.5 times that period, it considers the client gone.

Payload: how many bytes does one reading take?

Let's say the value we send is a 4-character light reading like 1234. In a POST request made with the ESP32's HTTPClient library, the request line plus the Host, User-Agent, Connection, Accept-Encoding, Content-Type and Content-Length headers take about 200 bytes; the server's response headers add another 100–300 bytes. If the connection is set up every time, around 7 extra packets go out for the TCP handshake and teardown; with HTTPS the TLS handshake adds a few kilobytes of certificate data. Publishing the same value with MQTT to the bluegrays/salon/isik topic at QoS 0 gives a packet of 2 bytes fixed header, 2 bytes topic length, 20 bytes topic name and 4 bytes of data: 28 bytes in total. With WebSocket, a text frame from the client is 10 bytes (2 bytes header, 4 bytes mask key, 4 bytes data); frames from the server to the client have no mask, so 6 bytes are enough.

MethodSent at application layerConnection costNote
HTTP POST (incl. response)About 300–500 bytesTCP handshake for every request (+ TLS with HTTPS)The connection can be reused with keep-alive
MQTT PUBLISH, QoS 028 bytesConnect once, then only PINGREQ (2 bytes)A short topic name makes the packet even smaller
MQTT PUBLISH, QoS 128 + 2 bytes packet ID + 4-byte PUBACKOnceAcknowledged delivery
WebSocket frame6–10 bytesOne HTTP Upgrade handshakeDelivered straight to the browser

Latency and battery consumption

What decides latency is usually not the protocol itself but whether the connection is already open. Imagine a server with a 50 ms round-trip time (RTT) over the internet. A new HTTP request first needs the TCP handshake (1 RTT), then the request and response (1 RTT): about 100 ms. With HTTPS, TLS 1.2 adds two more RTTs and the total reaches 200 ms; on the ESP32 the certificate work can add a few hundred milliseconds on top. On an open MQTT or WebSocket connection, the message travels one way and reaches the receiver in half an RTT, around 25 ms. On a local network these times drop to a few milliseconds.

On the battery side the math can flip. The ESP32 draws an average of 100–150 mA with Wi-Fi active, and a persistent MQTT or WebSocket connection requires Wi-Fi to stay awake. Even in modem sleep it averages 20–30 mA, which drains a 2000 mAh battery in 3–4 days. But if the sensor wakes every 10 minutes, sends its data and goes back to deep sleep, each wake-up takes about 2 seconds at 120 mA, i.e. 0.067 mAh. 144 wake-ups a day come to about 9.6 mAh; adding the deep sleep current of a bare module, the same battery lasts close to 200 days on paper. In this scenario most of the time is spent connecting to Wi-Fi; the difference between a single HTTP request and an MQTT connect-publish-disconnect is only a few hundred bytes.

ScenarioSuitable methodAverage current (approx.)Runtime on 2000 mAh
Always connected, waiting for commandsMQTT or WebSocket20–30 mA (modem sleep)3–4 days
Always connected, Wi-Fi at full powerDoesn't matter100–150 mA13–20 hours
One reading every 10 minutes + deep sleepHTTP or a short MQTT session0.4 mAAbout 200 days (bare module)
Mains-powered deviceMQTT (if it also receives commands)NegligibleUnlimited
On development boards the USB-serial chip and the regulator can draw several mA even in deep sleep; the 200-day figure only applies to a bare ESP32 module or boards designed for low power. Don't promise any battery life before measuring your board's sleep current with a multimeter.

Same sensor data, three methods: the circuit

To keep the comparison fair, all three sketches use the same circuit: a voltage divider made of an LDR and a 10 kΩ resistor. The LDR goes to 3.3 V, the resistor to GND, and the midpoint to the ADC pin. On the ESP32 we use GPIO 34 because ADC2 pins can't be read while Wi-Fi is on, while GPIO 34 is on ADC1. For the HTTP example we assume an endpoint on your computer that accepts POST on port 8000 (e.g. an http in node in Node-RED or a few lines of Flask), and for the MQTT example that Mosquitto is running on the same computer. Replace the 192.168.1.50 address in the examples with your computer's IP.

ConnectionESP32Raspberry Pi Pico W
LDR one leg3V33V3(OUT)
LDR other leg + one end of 10 kΩGPIO 34 (ADC1)GP26 (ADC0)
Other end of 10 kΩGNDGND
Onboard LED (command test)GPIO 2 (on most boards)Not used

1. Sending with HTTP POST (ESP32)

The first sketch uses the HTTPClient library that comes with the ESP32 core; no extra library is needed. Every 10 seconds it POSTs the light value as a JSON body and prints the server's status code and how many milliseconds the request took to the Serial Monitor. Measuring that time gives you a concrete number when you compare it with MQTT. For larger data, using ArduinoJson is safer than building JSON by hand.

C++ (Arduino IDE)
1// ESP32: LDR ölçümünü HTTP POST ile sunucuya gönderir
2// ESP32: sends the LDR reading to a server with HTTP POST
3#include <WiFi.h>
4#include <HTTPClient.h>
5
6const char* WIFI_ADI = "WIFI_ADIN";       // Wi-Fi adı / Wi-Fi name
7const char* WIFI_SIFRE = "WIFI_SIFREN";   // Wi-Fi şifresi / Wi-Fi password
8const char* SUNUCU = "http://192.168.1.50:8000/olcum";   // bilgisayarındaki sunucu / server on your computer
9const int LDR_PIN = 34;                   // ADC1 pini / ADC1 pin
10const unsigned long ARALIK = 10000;       // 10 saniyede bir / every 10 seconds
11unsigned long sonGonderim = 0;
12
13void setup() {
14  Serial.begin(115200);
15  analogReadResolution(12);               // 0-4095
16  WiFi.begin(WIFI_ADI, WIFI_SIFRE);
17  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
18  Serial.println();
19  Serial.println(WiFi.localIP());
20}
21
22void loop() {
23  if (millis() - sonGonderim < ARALIK) return;
24  sonGonderim = millis();
25
26  int isik = analogRead(LDR_PIN);
27  String govde = "{\"cihaz\":\"salon\",\"isik\":" + String(isik) + "}";
28
29  HTTPClient http;
30  unsigned long t0 = millis();
31  http.begin(SUNUCU);
32  http.addHeader("Content-Type", "application/json");
33  int kod = http.POST(govde);             // istek gönder, yanıtı bekle / send request, wait for response
34  unsigned long sure = millis() - t0;
35  Serial.printf("isik=%d  HTTP %d  %lu ms\n", isik, kod, sure);
36  if (kod > 0) Serial.println(http.getString());   // sunucunun yanıtı / server response
37  http.end();                             // bağlantıyı kapat / close the connection
38}
39

2. Publishing with MQTT (ESP32 + PubSubClient)

For the second sketch, install Nick O'Leary's PubSubClient library from the Library Manager. The sketch connects to the broker once, leaves offline on the status topic as its last will, publishes online once connected and subscribes to the LED topic. On your computer you can watch incoming values with mosquitto_sub -h localhost -t "bluegrays/#" -v and switch the board's LED instantly with mosquitto_pub -h localhost -t bluegrays/salon/led -m 1. By default Mosquitto 2.x only accepts connections from its own computer; if you don't add the lines listener 1883 and allow_anonymous true to mosquitto.conf, the ESP32 can't connect and you'll see error code -2 in the Serial Monitor. mqtt.loop() must be called on every loop; it handles incoming messages and keep-alive packets. The full Home Assistant and ESPHome integration is in the ESP32 MQTT and Home Assistant guide.

C++ (Arduino IDE)
1// ESP32: LDR ölçümünü MQTT ile yayınlar, LED komutuna abone olur (PubSubClient)
2// ESP32: publishes the LDR reading over MQTT, subscribes to an LED command (PubSubClient)
3#include <WiFi.h>
4#include <PubSubClient.h>
5
6const char* WIFI_ADI = "WIFI_ADIN";
7const char* WIFI_SIFRE = "WIFI_SIFREN";
8const char* BROKER = "192.168.1.50";      // Mosquitto çalışan bilgisayar / computer running Mosquitto
9const int BROKER_PORT = 1883;
10const char* KONU_ISIK = "bluegrays/salon/isik";    // yayın / publish
11const char* KONU_LED = "bluegrays/salon/led";      // abonelik / subscribe
12const char* KONU_DURUM = "bluegrays/salon/durum";  // online / offline
13const int LDR_PIN = 34;
14const int LED_PIN = 2;                    // çoğu ESP32 kartında dahili LED / onboard LED on most ESP32 boards
15
16WiFiClient wifiIstemci;
17PubSubClient mqtt(wifiIstemci);
18unsigned long sonGonderim = 0;
19
20// Abone olunan konuya mesaj gelince çalışır / runs when a message arrives on a subscribed topic
21void mesajGeldi(char* konu, byte* veri, unsigned int uzunluk) {
22  String mesaj;
23  for (unsigned int i = 0; i < uzunluk; i++) mesaj += (char)veri[i];
24  Serial.printf("[%s] %s\n", konu, mesaj.c_str());
25  if (strcmp(konu, KONU_LED) == 0) digitalWrite(LED_PIN, mesaj == "1" ? HIGH : LOW);
26}
27
28void baglan() {
29  while (!mqtt.connected()) {
30    String id = "esp32-salon-" + String((uint32_t)ESP.getEfuseMac(), HEX);
31    // Son vasiyet: bağlantı koparsa broker "offline" yayınlar / last will: broker publishes "offline" if we drop
32    if (mqtt.connect(id.c_str(), KONU_DURUM, 1, true, "offline")) {
33      mqtt.publish(KONU_DURUM, "online", true);   // kalıcı (retained) mesaj / retained message
34      mqtt.subscribe(KONU_LED);
35      Serial.println("MQTT bagli / connected");
36    } else {
37      Serial.printf("MQTT hata / error %d, 2 sn sonra tekrar / retry in 2 s\n", mqtt.state());
38      delay(2000);
39    }
40  }
41}
42
43void setup() {
44  Serial.begin(115200);
45  pinMode(LED_PIN, OUTPUT);
46  analogReadResolution(12);
47  WiFi.begin(WIFI_ADI, WIFI_SIFRE);
48  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
49  Serial.println();
50  mqtt.setServer(BROKER, BROKER_PORT);
51  mqtt.setCallback(mesajGeldi);
52  mqtt.setKeepAlive(30);                  // 30 sn sessizlikte PINGREQ / PINGREQ after 30 s of silence
53}
54
55void loop() {
56  if (!mqtt.connected()) baglan();
57  mqtt.loop();                            // gelen mesajlar ve keep-alive / incoming messages and keep-alive
58
59  if (millis() - sonGonderim >= 10000) {
60    sonGonderim = millis();
61    char deger[8];
62    snprintf(deger, sizeof(deger), "%d", analogRead(LDR_PIN));
63    mqtt.publish(KONU_ISIK, deger);
64    Serial.printf("yayin / publish %s = %s\n", KONU_ISIK, deger);
65  }
66}
67

3. Live dashboard with WebSocket (ESP32)

For the third sketch, install Markus Sattler's WebSockets library. This time there's no server in the middle: the ESP32 serves a small web page on port 80 and runs a WebSocket server on port 81. When you open the IP address shown in the Serial Monitor in your phone's browser, the light value updates by itself twice a second; when you press the buttons, the command travels back to the ESP32 over the same channel. The page never reloads and nothing is polled. For busier dashboards you'll find the ESPAsyncWebServer-based version in the ESP32 Async Web Server and WebSocket article.

C++ (Arduino IDE)
1// ESP32: LDR değerini WebSocket ile tarayıcıya canlı iter, tarayıcıdan LED komutu alır
2// ESP32: pushes the LDR value live to the browser over WebSocket, takes LED commands from it
3// Kütüphane / library: WebSockets (Markus Sattler)
4#include <WiFi.h>
5#include <WebServer.h>
6#include <WebSocketsServer.h>
7
8const char* WIFI_ADI = "WIFI_ADIN";
9const char* WIFI_SIFRE = "WIFI_SIFREN";
10const int LDR_PIN = 34;
11const int LED_PIN = 2;
12
13WebServer web(80);              // sayfayı sunar / serves the page
14WebSocketsServer ws(81);        // canlı veri kanalı / live data channel
15unsigned long sonGonderim = 0;
16
17const char SAYFA[] PROGMEM = R"rawliteral(
18<!DOCTYPE html><html><head><meta charset="utf-8">
19<meta name="viewport" content="width=device-width,initial-scale=1"><title>BlueGrays WebSocket</title></head>
20<body style="font-family:sans-serif;text-align:center">
21<h2>Isik / Light</h2><p id="d" style="font-size:48px">-</p>
22<button onclick="s.send('led:1')">LED ON</button>
23<button onclick="s.send('led:0')">LED OFF</button>
24<script>
25var s = new WebSocket('ws://' + location.hostname + ':81/');
26s.onmessage = function (e) { document.getElementById('d').textContent = e.data; };
27</script></body></html>
28)rawliteral";
29
30// WebSocket olayları / WebSocket events
31void wsOlay(uint8_t no, WStype_t tur, uint8_t* veri, size_t uzunluk) {
32  if (tur == WStype_CONNECTED) {
33    Serial.printf("istemci %u baglandi / client connected\n", no);
34  } else if (tur == WStype_DISCONNECTED) {
35    Serial.printf("istemci %u ayrildi / client left\n", no);
36  } else if (tur == WStype_TEXT) {
37    String komut;
38    for (size_t i = 0; i < uzunluk; i++) komut += (char)veri[i];
39    if (komut == "led:1") digitalWrite(LED_PIN, HIGH);
40    if (komut == "led:0") digitalWrite(LED_PIN, LOW);
41  }
42}
43
44void setup() {
45  Serial.begin(115200);
46  pinMode(LED_PIN, OUTPUT);
47  analogReadResolution(12);
48  WiFi.begin(WIFI_ADI, WIFI_SIFRE);
49  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
50  Serial.print("\nTarayicida ac / open in browser: http://");
51  Serial.println(WiFi.localIP());
52
53  web.on("/", []() { web.send_P(200, "text/html", SAYFA); });
54  web.begin();
55  ws.begin();
56  ws.onEvent(wsOlay);
57}
58
59void loop() {
60  web.handleClient();
61  ws.loop();
62  if (millis() - sonGonderim >= 500) {    // saniyede 2 güncelleme / 2 updates per second
63    sonGonderim = millis();
64    String deger = String(analogRead(LDR_PIN));
65    ws.broadcastTXT(deger);               // bağlı tüm tarayıcılara / to every connected browser
66  }
67}
68

Raspberry Pi Pico W: HTTP and MQTT (MicroPython)

On the Pico W you can run the same comparison in one file: just set the YONTEM variable to "http" or "mqtt". For HTTP, the urequests module comes with the Pico W build of MicroPython. umqtt.simple isn't included in some builds; install it in Thonny's shell with import mip followed by mip.install("umqtt.simple"). The ADC's read_u16() value ranges from 0 to 65535; shifting it right by four bits gives you the same 0–4095 scale as the ESP32. The MQTT connection is opened once before the loop, while HTTP sends a new request for every reading and frees memory with r.close(). The details are in the Pico W MQTT guide.

MicroPython
1# Raspberry Pi Pico W: aynı LDR verisini HTTP ya da MQTT ile gönderir (MicroPython)
2# Raspberry Pi Pico W: sends the same LDR reading over HTTP or MQTT (MicroPython)
3import network
4import time
5import urequests
6from machine import ADC
7from umqtt.simple import MQTTClient
8
9WIFI_ADI = "WIFI_ADIN"
10WIFI_SIFRE = "WIFI_SIFREN"
11YONTEM = "mqtt"                       # "http" ya da "mqtt" / "http" or "mqtt"
12SUNUCU = "http://192.168.1.50:8000/olcum"
13BROKER = "192.168.1.50"
14KONU = b"bluegrays/salon/isik"
15
16ldr = ADC(26)                         # GP26 = ADC0
17wlan = network.WLAN(network.STA_IF)
18wlan.active(True)
19wlan.connect(WIFI_ADI, WIFI_SIFRE)
20while not wlan.isconnected():
21    time.sleep(0.5)
22print("IP:", wlan.ifconfig()[0])
23
24mqtt = None
25if YONTEM == "mqtt":
26    mqtt = MQTTClient("pico-salon", BROKER, keepalive=60)
27    mqtt.connect()                    # bağlantı bir kez açılır / connection opened once
28
29while True:
30    isik = ldr.read_u16() >> 4        # 0-4095, ESP32 ile aynı ölçek / same scale as ESP32
31    t0 = time.ticks_ms()
32    if YONTEM == "http":
33        r = urequests.post(SUNUCU, json={"cihaz": "pico", "isik": isik})
34        print(isik, "HTTP", r.status_code, time.ticks_diff(time.ticks_ms(), t0), "ms")
35        r.close()                     # belleği boşalt / free the memory
36    else:
37        mqtt.publish(KONU, str(isik))
38        print(isik, "MQTT", time.ticks_diff(time.ticks_ms(), t0), "ms")
39    time.sleep(10)
40

Which one should you choose? Decision table by project

ProjectRecommendedWhy?
Battery sensor sending a few readings an hourHTTP (or a short MQTT session)Connect, send, sleep; no extra server or library needed
ThingSpeak, Google Sheets, weather APIHTTPThese services offer HTTP APIs
Controlling a relay, LED or door lock from your phoneMQTTCommands arrive instantly, no polling
Dozens of devices with Home AssistantMQTTTopic structure, retained messages and LWT for device status
Live web dashboard on the ESP32WebSocketNative browser support, no broker needed
Driving a robot car from the browserWebSocketLow-latency, two-way command stream
Connecting to an MQTT broker from a browserMQTT over WebSocketBrowsers can't open raw TCP; the broker's WebSocket port is used

Common wrong choices

  • Polling with HTTP to wait for commands: One request per second wears out both the server and the Wi-Fi, and makes it impossible to put the ESP32 to sleep. If you need to receive commands, use MQTT or WebSocket.
  • Keeping the connection open on a battery sensor: Keeping Wi-Fi awake for keep-alive drains the battery within days. For infrequent data, wake up, send and go back to deep sleep.
  • Unprotected control on a public broker: On public brokers like broker.hivemq.com, anyone who knows the topic name can switch your relay. In a real project use a username, password and TLS (8883), or run your own broker.
  • Using WebSocket for device-to-device communication: For two ESP32s or ten sensors to talk, a single MQTT broker is far tidier than writing a server on each of them.
  • Choosing QoS 2 for everything: The four-step handshake increases traffic and latency. QoS 0 is enough for frequent sensor data, QoS 1 for important commands.
  • Choking mqtt.loop() or ws.loop() with delay(): A long delay() misses the keep-alive and the connection drops; do your timing with millis().
On the ESP32, ADC2 pins (GPIO 0, 2, 4, 12–15, 25–27) can't be read with analogRead while Wi-Fi is on and return error values. In any networked project, connect analog sensors to the ADC1 pins between GPIO 32 and 39.

If you'd like to see the Wi-Fi connection, an HTTP request and live data over WebSocket separately before experimenting with network protocols, the BlueGrays app has the ESP32 Wi-Fi connection, HTTPClient weather and WebSocket counter projects with step-by-step circuit diagrams and code; building this comparison on top of those projects is very easy.

Frequently asked questions

What is the difference between MQTT and HTTP?

HTTP is a request-response model: the device sends a request to the server every time and waits for a reply. MQTT is a publish-subscribe model: the device stays connected to a broker, publishes messages to topics and instantly receives messages on the topics it subscribes to. MQTT has much smaller overhead and is well suited to sending commands from the server to the device.

Is MQTT faster than HTTP?

With the connection open, MQTT is much faster, because the message travels one way without a new handshake and the packet is only a few dozen bytes. HTTP may need a TCP handshake for each request, plus a TLS handshake with HTTPS. For infrequent sending, though, most of the time in both cases is spent connecting to Wi-Fi.

What is the difference between WebSocket and MQTT?

WebSocket is a two-way transport channel between two endpoints; you design what the messages mean, where they go and how delivery is guaranteed. MQTT is a messaging protocol with ready-made rules such as topics, subscriptions, QoS, retained messages and last will. They're also used together: browsers connect to MQTT brokers over WebSocket.

Does MQTT need the internet?

No. If you install Mosquitto on a computer or a Raspberry Pi at home, all devices communicate over the local network only. If you want access from outside, you use a cloud broker or a secure tunnel.

What is the best MQTT library for the ESP32?

The most common choice is Nick O'Leary's PubSubClient; it's small, simple and well documented, but it can only subscribe with QoS 0 and 1 and publishes at QoS 0. If you need an asynchronous design and QoS 1/2 publishing, go for AsyncMqttClient or the esp-mqtt component of ESP-IDF.

Can you send remote commands to an ESP32 with HTTP?

Yes, in two ways: turn the ESP32 into a web server and send requests from a browser, or have the ESP32 periodically ask a cloud address whether there's a new command. The first is easy on a local network; the second is slow and inefficient. For instant commands over the internet, MQTT is the better fit.

See all projects
Reading Light Intensity with the ESP32 LDR Module
ES-11Beginner

Reading Light Intensity with the ESP32 LDR Module

Real-time monitoring of the LDR module's raw ADC value and relative light percentage calculated from dark and light reference values in the Serial Monitor. This percentage is not a lux measurement. Teaches the module’s calibration logic. It is ideal to complete this before Project 10, as it is used to determine the threshold value.

4.6(36)
56
ESP32 Wi-Fi STA Connection (with LCD Screen)
ES-25Advanced

ESP32 Wi-Fi STA Connection (with LCD Screen)

In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

4.4(21)
40
ESP32 Asynchronous Web Server (with IP Display on LCD)
ES-27Advanced

ESP32 Asynchronous Web Server (with IP Display on LCD)

In this project, we’re turning the ESP32 into an asynchronous web server that you can control from your phone or computer on the same Wi-Fi network. Thanks to the ESPAsyncWebServer library, the server can process multiple requests simultaneously (unlike the classic WebServer.h, which blocks on a single request). You’ll be able to open the ESP32’s IP address in a browser and click the ON/OFF buttons (the /on and /off routes) to turn the LED connected to GPIO 5 on and off.

4.8(16)
27
ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)
ES-28Advanced
Premium

ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)

In this project, two buttons wired to the ESP32 (GPIO 5 counts up, GPIO 4 counts down) change a counter. The value updates instantly both on a 16x2 I2C LCD and, through the WebSocket support of ESPAsyncWebServer, in every connected browser without reloading the page. Instead of HTTP polling a single persistent connection is used, and the ESP32 sends the new value to everyone with ws.textAll().

4.5(14)
23
ESP32 mDNS: Accessing the Device via bluegrays-esp.local (with LCD Screen)
ES-29Advanced
Premium

ESP32 mDNS: Accessing the Device via bluegrays-esp.local (with LCD Screen)

In this project we add an mDNS (Multicast DNS) service to the ESP32, so you reach it by a readable host name like bluegrays-esp.local instead of an IP address. Even if the IP assigned by DHCP changes, the device always answers to the same name. A small web server on the board lets you control the LED from your browser at http://bluegrays-esp.local/.

4.8(14)
23
ESP32 HTTPClient + Weather API (with LCD Screen)
ES-31Advanced
Premium

ESP32 HTTPClient + Weather API (with LCD Screen)

In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. The JSON response is parsed with ArduinoJson v7, and the city, temperature, humidity, weather and wind are shown on an I2C LCD. wttr.in needs no API key; just type the name of any city.

4.7(13)
20
ESP32 HTTPClient + Weather API (with SSD1306 OLED Display)
ES-32Advanced
Premium

ESP32 HTTPClient + Weather API (with SSD1306 OLED Display)

In this project the ESP32 makes a REST API call over the internet to a weather API (wttr.in) using HTTPClient.h. Unlike the I2C LCD version, it uses an SSD1306 OLED (128×64) display, with large text and vector icons for a richer look. Seven weather icons (sunny, rainy, snowy and more) are drawn on the fly, with no bitmap files.

4.3(10)
22
ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)
ES-33Advanced
Premium

ESP32 Deep Sleep — Battery Saving (OLED + RTC RAM Counter)

The ESP32's Deep Sleep mode shuts down the CPU and most peripherals, cutting current draw to about 10µA, which is vital for battery-powered IoT devices. This project uses three wake-up sources: a timer (15 s), an external pin (EXT0, the button on GPIO 33) and a touch pin (T0/GPIO 4). Counters marked with RTC_DATA_ATTR survive deep sleep.

4.3(10)
17