Most ESP32 tutorials stop at one board printing a sensor value to the Serial Monitor. The moment you want a second device, a dashboard, or a reading you can check from your phone, the questions change: how does one board find the other, what format does the data travel in, and what happens when the network drops? This project answers those questions in the simplest way that still works properly.
You will build a two-board system on your existing Wi-Fi network, with no cloud account, no MQTT broker and no phone app. The first ESP32, the sensor node, reads an IR obstacle sensor and an MQ135 air quality sensor once a second and sends both numbers to the second board with a plain HTTP request. The second ESP32, the server node, stores the latest values and serves a live dashboard that any phone or laptop on the same network can open in a browser.
Most of the trouble people hit with this build is not the code. It is the order of operations (the sensor node needs the server's IP address before it can send anything), a router that quietly blocks device-to-device traffic, and an MQ135 that has not warmed up. This guide deals with all three up front, so your first upload has a good chance of working.
What you will learn:
- How to send sensor data between two ESP32s with plain HTTP GET requests
- How to host a web server on an ESP32 with
WebServer.h - How to read a digital IR sensor (GPIO18) and an analog MQ135 sensor (ADC1, GPIO32)
- How to serve a self-refreshing HTML dashboard straight from the microcontroller
- How to test each half of the system separately, so faults are easy to isolate
- How to make the system reliable: fixed IP addresses, averaging, timeouts and a basic shared key
Time: about 90 minutes. Skill level: intermediate. Before you start: you should be able to upload a sketch to an ESP32. If you have not set up the Arduino IDE for ESP32 yet, the setup section below covers exactly the settings that matter.
How the System Works
Two ESP32 boards join the same 2.4 GHz Wi-Fi router and play two different roles. The sensor node (ESP32 #1) is an HTTP client. It owns the wiring: the IR sensor and the MQ135 are connected to it, and once a second it builds a web address such as http://192.168.1.50/update?ir=1&mq=412 and requests it. The server node (ESP32 #2) is the HTTP server. It needs no sensors at all. It listens on port 80, takes the two numbers out of every /update request, keeps them in memory and answers OK.
Separately, when you type the server's address into a browser, the same board returns an HTML page with the latest values that refreshes itself every two seconds. That page is the dashboard. There is no database, no file system and no app: the whole system is one URL pattern and one HTML string.
Keeping the two roles apart is the useful idea here. The sensor node can sit wherever the air matters (a workshop, a kitchen, a cupboard full of electronics) while the server node sits anywhere with power and Wi-Fi. Adding a second sensor node later takes only a few extra lines on the server.
Why plain HTTP?
There are several ways to move data between ESP32 boards, and each has trade-offs:
| Method | Needs a router | Needs a broker | Complexity | Good for |
|---|---|---|---|---|
| HTTP over Wi-Fi (this project) | Yes | No | Low | Simple links you can test with any browser |
| MQTT | Yes | Yes | Medium | Many devices, publish/subscribe, home automation |
| ESP-NOW | No | No | Medium | Short messages between boards without any network |
HTTP wins for learning because you can debug it with a browser. Type the /update URL by hand and you will see the server react, which makes problems easy to isolate. The costs are overhead (each message carries HTTP headers) and the fact that both boards must be on the same network. When you outgrow it, the ideas carry straight over to MQTT or ESP-NOW. The ESP-NOW version of this idea removes the router entirely.
Why GET and not POST?
Strictly speaking, a request that changes something on the server should be a POST. This project uses GET with the values in the query string because it makes the link testable from any browser address bar, and because the data is two small integers. Once your payload grows, or you send anything you would not want visible in a URL, switch to POST. The ESP32 HTTP GET and POST guide shows both.
Components
6 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
Parts notes
Any ESP32 DevKit with 30 or 38 pins works for both roles, and the two boards do not have to match. The sketches use GPIO numbers, not the silkscreen labels some boards print (such as D18), so if your board's labels differ, follow the GPIO number.
A few details about the modules save confusion later:
- IR obstacle sensor. Usually a three-pin module (VCC, GND, OUT) with a small potentiometer and two LEDs: one for power and one that lights when it detects something. That indicator LED is the quickest way to test the sensor before the ESP32 is involved.
- MQ135 module. Usually four pins: VCC, GND, DOUT and AOUT. This project uses AOUT, the analog output. DOUT is a simple on/off signal from an onboard comparator, and on most modules the potentiometer only sets that comparator's threshold, so turning it does not change the analog reading.
- Power. Each board can run from a phone charger or a laptop USB port. The MQ135 heater alone draws roughly 150 mA, so use a decent cable. A thin or very long USB cable is a common cause of random resets on the sensor node.
Understanding the Two Sensors
The IR obstacle sensor
This module shines infrared light and watches for a reflection. The output pin is active LOW: it reads 0 when an object is detected and 1 when the path is clear, as on most modules of this type. The small potentiometer sets the detection distance, from a few centimetres up to a few tens of centimetres depending on the module. If your module behaves the other way round, either adjust the potentiometer or invert the logic in your code.
Two behaviours are worth knowing before you blame the code. Black and other matte, dark surfaces absorb infrared and can be almost invisible to the sensor, while white or shiny surfaces reflect strongly. Direct sunlight and some bright lamps contain plenty of infrared and can make the module trigger constantly. Test indoors, away from windows, and use the indicator LED as feedback while you tune the potentiometer.
The MQ135 air quality sensor
The MQ135 is a heated metal-oxide sensor. A small heater inside brings the sensing layer up to temperature, and the layer's resistance drops when gases such as ammonia, nitrogen oxides, alcohol, benzene vapour, smoke and CO₂ are present. The module turns that resistance into a voltage on its AOUT pin.
Three facts shape how you should use it:
- It is an indicator, not a CO₂ meter. It responds to many gases at once, so the number tells you "the air changed", not "the air has 800 ppm CO₂".
- It needs warm-up. The heater is rated for 5 V and draws roughly 150 mA. A brand-new sensor benefits from 24 to 48 hours of burn-in, and every power-up needs a few minutes before readings settle.
- Supply voltage changes the numbers. At 3.3 V the heater runs on less than half the power it gets at 5 V, so the sensor is cooler, less sensitive and reads differently.
Wiring the Sensor Node (ESP32 #1)
Only the sensor node is wired. Connect the two modules to the ESP32 like this:
| Sensor pin | ESP32 pin |
|---|---|
| IR OUT | GPIO18 |
| MQ135 AOUT | GPIO32 |
| VCC (both sensors) | 3V3 |
| GND (both sensors) | GND |
The second board, the server node, needs no wiring at all. Power it over USB and that is it.
Check before you power up. Confirm VCC and GND on both modules before you plug in the USB cable. Reversed polarity can destroy a sensor module in moments.
Why 3.3 V for the MQ135?
This build powers both modules from 3.3 V because the MQ135's analog output cannot rise above its own supply voltage, so at 3.3 V it can never exceed 3.3 V. That keeps the ESP32's ADC safe. The trade-off is lower sensitivity.
If you want the sensor at its designed 5 V heater voltage, connect its VCC to the board's VIN pin, but then AOUT can reach about 5 V, which is too high for an ESP32 pin. Put a voltage divider on AOUT first: for example 10 kΩ from AOUT to the ADC pin and 15 kΩ from the ADC pin to GND, which scales 5 V down to about 3 V. The divider scales every reading, so you must recalibrate the thresholds in the table further down.
💡 Tip
GPIO32 belongs to ADC1, which keeps working while Wi-Fi is active. Avoid ADC2 pins (GPIO0, 2, 4, 12, 13, 14, 15, 25, 26, 27) for analog readings in a Wi-Fi project, because the Wi-Fi radio shares that converter and the readings become unreliable or fail.
Setting Up the Arduino IDE
If this is your first ESP32 project in the Arduino IDE, add ESP32 support once and both boards are covered:
- Install the Arduino IDE (version 2.x is the easiest to work with) from arduino.cc.
- Open File → Preferences and add this address to "Additional boards manager URLs":
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json - Open Tools → Board → Boards Manager, search for "esp32" and install esp32 by Espressif Systems.
- Plug in an ESP32, choose Tools → Board → ESP32 Arduino → ESP32 Dev Module, then pick its port under Tools → Port. If no port appears, install the USB driver for your board's USB-to-serial chip (CP2102 and CH340 are the common ones).
- Open the Serial Monitor and set it to 115200 baud.
You do not need to install any extra libraries. WiFi.h, WebServer.h and HTTPClient.h all ship with the ESP32 board package.
You will be handling two identical boards, so label them. A strip of tape reading "SERVER" and "SENSOR" prevents the classic mistake of uploading the right sketch to the wrong board. If an upload sits on "Connecting....", hold the BOOT button on the board until the upload starts.
Upload Order Matters
The sensor node needs to know the server's IP address, and you only learn that address after the server has connected to your router. So follow this order the first time. (If you later give the server a fixed IP, as described further down, the order stops mattering.)
Steps
- 1Set your Wi-Fi name and password in the server sketch and upload it to ESP32 #2.
- 2Open the Serial Monitor at 115200 baud. When it connects it prints the server IP, for example 192.168.1.50. Write it down.
- 3Put the same Wi-Fi details and that IP address into the sensor sketch (the serverIP line) and upload it to ESP32 #1.
- 4Open the Serial Monitor on ESP32 #1. You should see IR and MQ135 values and HTTP: 200 once a second.
- 5On any phone or laptop connected to the same Wi-Fi, open http://<server-ip>/ . Use http, not https.
If everything is working, the two Serial Monitors look something like this. Your addresses will differ.
Server node (ESP32 #2):
Server IP: 192.168.1.50Sensor node (ESP32 #1):
....
Connected. IP: 192.168.1.51
IR: 1 MQ135: 412
HTTP: 200
IR: 1 MQ135: 415
HTTP: 200Code for the Server Node (Dashboard and Data Receiver)
Upload this to ESP32 #2. It needs only the libraries built into the ESP32 board package. The only lines you must edit are ssid and password.
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "YourSSID";
const char* password = "YourPassword";
WebServer server(80);
int irValue = 0, mqValue = 0;
unsigned long lastUpdate = 0;
void handleRoot() {
String page = "<!DOCTYPE html><html><head>";
page += "<meta http-equiv='refresh' content='2'>";
page += "<title>ESP32 Dashboard</title>";
page += "<style>body{background:#111;color:white;font-family:Arial;text-align:center;padding-top:40px;}";
page += ".box{width:350px;margin:auto;background:#222;padding:20px;border-radius:10px;}";
page += ".value{font-size:32px;font-weight:bold;color:#00ff88;}</style></head><body>";
page += "<div class='box'><h1>ESP32 SENSOR SERVER</h1>";
page += "<p>IR SENSOR</p><div class='value'>" + String(irValue) + "</div><br>";
page += "<p>MQ135 VALUE</p><div class='value'>" + String(mqValue) + "</div><br>";
page += "<p>LAST UPDATE</p><div class='value'>" + String((millis()-lastUpdate)/1000) + " sec</div>";
page += "</div></body></html>";
server.send(200, "text/html", page);
}
void handleUpdate() {
if (server.hasArg("ir")) irValue = server.arg("ir").toInt();
if (server.hasArg("mq")) mqValue = server.arg("mq").toInt();
lastUpdate = millis();
server.send(200, "text/plain", "OK");
}
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); }
Serial.println("Server IP: " + WiFi.localIP().toString());
server.on("/", handleRoot);
server.on("/update", handleUpdate);
server.begin();
}
void loop() {
server.handleClient();
}Code for the Sensor Node (Client)
Upload this to ESP32 #1 after you know the server's IP address. Edit three lines: ssid and password (the same network as the server) and serverIP (the address the server printed).
#include <WiFi.h>
#include <HTTPClient.h>
#define IR_PIN 18
#define MQ_PIN 32
const char* ssid = "YourSSID";
const char* password = "YourPassword";
const char* serverIP = "192.168.1.50"; // replace with your server ESP32's IP
unsigned long previousMillis = 0;
const long interval = 1000;
void setup() {
Serial.begin(115200);
pinMode(IR_PIN, INPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println("\nConnected. IP: " + WiFi.localIP().toString());
}
void loop() {
unsigned long now = millis();
if (now - previousMillis >= interval) {
previousMillis = now;
int irValue = digitalRead(IR_PIN);
int mqValue = analogRead(MQ_PIN);
Serial.printf("IR: %d MQ135: %d\n", irValue, mqValue);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "http://" + String(serverIP) +
"/update?ir=" + irValue + "&mq=" + mqValue;
http.begin(url);
int code = http.GET();
Serial.println("HTTP: " + String(code));
http.end();
}
}
}Test the Server by Hand
Before you trust the sensors, prove the server works on its own. With the server node running, open this address in a browser on the same network, replacing the IP with yours:
http://192.168.1.50/update?ir=0&mq=999
The browser shows OK. Now open http://192.168.1.50/. The dashboard shows an IR value of 0 and an MQ135 value of 999, with "LAST UPDATE" counting up from a few seconds. You have just played the part of the sensor node by hand.
This two-minute test splits every future problem in half. If the manual request works but the sensor node's does not, the fault is on the sensor side: the serverIP, the Wi-Fi credentials or the wiring. If even the manual request fails, look at the server, the router or the network. Once the sensor node is sending, it overwrites your test values within a second.
How the Code Works
The sensor node
The loop uses millis() instead of delay() to take a reading every 1000 ms. This non-blocking pattern keeps the board responsive and lets you add other tasks later. Each cycle it reads the digital IR pin and the analog MQ135 pin, prints both, builds a URL such as http://192.168.1.50/update?ir=1&mq=412, and sends it with HTTPClient. The value returned by http.GET() is the HTTP status code: 200 means success, and a negative number means the request never reached the server (-1 is the usual "could not connect").
The request is only sent while WiFi.status() is WL_CONNECTED. If the router drops the connection, the sketch skips sending instead of hanging, the ESP32 core reconnects in the background, and the readings resume by themselves.
There is no JSON and no parsing. The data travels in the URL's query string, which is why this project is so easy to follow and to test by hand.
The server node
WebServer server(80) listens on port 80 and maps two URL paths to functions:
/updatecallshandleUpdate(). It checks that the arguments exist withhasArg(), converts them with.toInt(), records the time withmillis(), and repliesOK./callshandleRoot(), which builds the dashboard page as one long string. The<meta http-equiv='refresh' content='2'>tag makes the browser reload the page every two seconds, so the values appear to update live.
The loop() contains only server.handleClient(). That one call checks whether a request has arrived and runs the matching handler.
Two details are worth knowing. First, "LAST UPDATE" is calculated as millis() - lastUpdate, so until the first reading arrives it counts from boot. If that number keeps growing, the sensor node is not getting through. Second, the values live only in RAM: if the server restarts, it shows zeros until the next update arrives, which takes about a second once the sensor node is running.
Reading the Numbers
IR sensor
| Value | Meaning |
|---|---|
0 | Object detected (the beam is reflected back) |
1 | Nothing detected |
To test it, hold your hand about 10 cm in front of the module. The indicator LED lights, and the Serial Monitor changes from IR: 1 to IR: 0.
MQ135 reading
The ESP32's 12-bit ADC turns the sensor voltage into a number from 0 to 4095. As a rough guide, with the module on 3.3 V as wired above:
| ADC value | Air quality |
|---|---|
| 0 to 600 | Clean |
| 600 to 1500 | Moderate (some CO₂, VOCs or other gases) |
| Above 1500 | Poor, ventilate the area |
These bands are approximate. Every sensor, supply voltage and room differs, so treat them as a starting point and calibrate for your own setup:
- Power the sensor node and let it warm up for at least 10 minutes in a well-ventilated room.
- Note the steady value in clean air. That is your baseline.
- Hold a cotton swab dipped in rubbing alcohol a few centimetres from the sensor (never touching it, and away from any heat source, because the alcohol is flammable) and watch the value rise. This confirms the sensor is responding.
- Set your own "moderate" and "poor" thresholds relative to your baseline rather than trusting the table.
Two separate MQ135 modules will not give the same number in the same room, so calibrate each one. For calibrated PPM figures you need a dedicated MQ135 library and a measured reference resistance (R0) obtained in clean air. Even then, remember the sensor is not selective.
Making It More Reliable
Give the server a fixed IP
Routers can hand out a different address after a restart, and then the sensor node would be talking to nothing. The simplest fix is a DHCP reservation in your router settings, which keeps the address out of your sketch entirely. Alternatively, add a static address to the server sketch, before WiFi.begin(). The ESP32 static IP guide covers this in more depth.
IPAddress local_IP(192, 168, 1, 50);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(192, 168, 1, 1);
// in setup(), before WiFi.begin():
WiFi.config(local_IP, gateway, subnet, dns);Choose an address outside your router's DHCP range and make sure it matches your own network's numbers.
Average the analog reading
The ESP32's ADC is noisy and slightly non-linear, and it is least trustworthy at the very bottom and very top of its range. Replace analogRead(MQ_PIN) with an average of several samples for a steadier dashboard:
int readMQ135() {
long sum = 0;
for (int i = 0; i < 16; i++) {
sum += analogRead(MQ_PIN);
delay(2);
}
return sum / 16;
}
// then in loop(): int mqValue = readMQ135();Show a label, not just a number
Add this helper above handleRoot() in the server sketch to translate both readings into words. The IR line then reads "Object detected" or "Clear" instead of 0 or 1:
String airLabel(int v) {
if (v < 600) return "Clean";
if (v < 1500) return "Moderate";
return "Poor - ventilate";
}
// in handleRoot(), replace the IR and MQ135 lines with:
page += "<p>IR SENSOR</p><div class='value'>" +
String(irValue == 0 ? "Object detected" : "Clear") + "</div><br>";
page += "<p>MQ135 VALUE</p><div class='value'>" + String(mqValue) +
" (" + airLabel(mqValue) + ")</div><br>";Be aware of timeouts
If the server is unreachable, http.GET() waits for its default timeout, about five seconds, before returning an error. During that time the sensor node does nothing else. For a quick improvement, call http.setTimeout(2000); right after http.begin(url);.
Power and placement
Put the MQ135 where air can actually reach it: not inside a sealed box, and not right next to the ESP32's voltage regulator or any other heat source, which warms the sensor and skews the readings. Keep it clear of flammable materials, because the heater gets warm. For a permanent install, use a 5 V phone charger rated for at least 1 A rather than a computer port, and a short, good-quality USB cable.
Security: What This Project Does and Does Not Protect
The server accepts values from anyone who can reach it, over unencrypted HTTP, and the dashboard has no login. On a home network with no ports forwarded to the outside, your Wi-Fi password is the access control, and that is acceptable for a learning project.
A small improvement is a shared key. The sensor node adds it to every request and the server rejects requests without it:
// Server: add near the top
const char* apiKey = "change-this-key";
// Server: replace handleUpdate() with
void handleUpdate() {
if (server.arg("key") != apiKey) {
server.send(403, "text/plain", "Forbidden");
return;
}
if (server.hasArg("ir")) irValue = server.arg("ir").toInt();
if (server.hasArg("mq")) mqValue = server.arg("mq").toInt();
lastUpdate = millis();
server.send(200, "text/plain", "OK");
}
// Sensor node: add the same key to the URL
String url = "http://" + String(serverIP) +
"/update?ir=" + irValue + "&mq=" + mqValue +
"&key=change-this-key";This stops another device on your network, or a typo in a different project, from overwriting your readings. It is not encryption: anyone who can sniff your Wi-Fi traffic can read the key, so treat it as protection against accidents rather than attackers. With the key in place, your manual test address from earlier needs &key=change-this-key on the end.
Do not forward this server's port on your router to reach it from outside. For remote viewing, use a VPN back into your home network, or put the dashboard behind a reverse proxy that adds real authentication and HTTPS.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Upload sits on "Connecting...." | The board is not in download mode, or the USB cable is charge-only | Hold the BOOT button until the upload starts, and try a data-capable cable |
| Serial Monitor shows garbage characters | Wrong baud rate | Set the Serial Monitor to 115200 |
| Dashboard shows stale data or "LAST UPDATE" keeps growing | Boards on different networks, or the router blocks device-to-device traffic | Put both on the same 2.4 GHz network. Turn off "AP isolation" or "client isolation", and avoid guest networks. |
| Dashboard loads, but IR and MQ135 stay at 0 | No update has arrived yet | Run the manual /update test, and check the sensor node's Serial Monitor for HTTP: 200 |
| ESP32 never connects to Wi-Fi | 5 GHz network or wrong password | The ESP32 supports only 2.4 GHz. Check the SSID and password. |
HTTP response is -1 | Wrong server IP, or the server has not finished booting | Read the server's current IP from its Serial Monitor and update serverIP. |
| Sensor node resets now and then | Weak power or a long, thin USB cable | Use a 5 V / 1 A supply and a short cable |
MQ135 always reads 0 or 4095 | Wiring fault, wrong pin, or sensor not warmed up | Check AOUT goes to GPIO32, allow warm-up, and confirm the module's power LED is on. |
| MQ135 values drift for the first minutes | Normal heater warm-up | Wait 5 to 10 minutes, and burn in a new sensor for 24 to 48 hours. |
| Analog values jump around | ADC noise | Average 16 samples as shown above. |
| Browser cannot open the dashboard | Using https:// or a different network | Use http:// with the exact IP. Some browsers auto-upgrade to HTTPS, so type the full address. |
| IR value is inverted, or always 0 | Module logic differs, or sunlight or a close surface is triggering it | Adjust the potentiometer, move away from windows, or invert the logic in your code. |
Going Further
- Alarm on motion. Add a buzzer to the server node that sounds when
irValue == 0. - Stale-data warning. Turn the "LAST UPDATE" value red when it passes ten seconds, so a dead sensor node is obvious at a glance.
- Log history. Save MQ135 readings to an SD card or the on-board flash with LittleFS to chart air quality over a day.
- Real-time updates. Replace the page refresh with WebSockets or small
fetch()calls, so values update without the page flicker. The ESP32 WebSocket tutorial shows how. - More sensors. Add an MQ2 (smoke) or MQ7 (carbon monoxide) module and send several values in one request:
/update?ir=1&mq=412&mq2=300. - Switch protocols. Rebuild the link with MQTT for many nodes, or ESP-NOW to remove the router entirely.
Frequently Asked Questions
Can the server and sensor run on one ESP32? Yes. The same board can read the sensors and host the dashboard. The two-board design is here to teach device-to-device communication.
How far apart can the boards be? As far as your Wi-Fi coverage reaches. Both just need a stable connection to the same router.
Can I add more sensor nodes? Yes. Give each one a different query name (for example ir2) or an ID, and extend handleUpdate() to store them.
What happens if the server restarts? The sensor node keeps sending, and http.GET() returns a negative number until the server is back. The dashboard shows zeros after the restart because the values are stored only in RAM, then recovers within a second of the next successful update.
Why GPIO32 for the MQ135? It is an ADC1 pin, so it keeps working while Wi-Fi is on. Any other ADC1 pin works too (GPIO32 to 39 on most DevKits), as long as you change MQ_PIN. Avoid ADC2 pins in any Wi-Fi project; the ADC1 vs ADC2 guide explains why.
Can I use an ESP8266 for either node? The pattern is identical, but the libraries have different names and the ESP8266 has a single analog pin with a different input range, so the MQ135 wiring changes.
Is the MQ135 safe to leave on all day? It is designed for continuous operation, but its heater gets warm, so keep it clear of flammable materials and ventilate the enclosure.
Summary
You built a complete two-board IoT system with no cloud: one ESP32 samples a digital IR sensor and an analog MQ135 sensor and sends the results over HTTP, and another turns those values into a live web dashboard. You learned which ADC pins are safe with Wi-Fi, why the MQ135 behaves differently at different supply voltages, how to calibrate against your own baseline, how to test the server by hand, and how to harden the link with fixed IPs, averaging, timeouts and a shared key.


