Temperature & humidity (DHT22)
Practicals 4, 7, 12Upload your first program, blink an LED and read a real sensor.
Run it in Wokwi
- Open a new ESP32 project in Wokwi.
- Copy sketch.ino below and paste it over the code in the
sketch.inotab. - Copy diagram.json and paste it over the
diagram.jsontab. - Library Manager tab → + → add DHT sensor library for ESPx.
- Press the green ▶ button. The first run waits 20–40 s in Wokwi’s free build queue.
Wiring on a real board
- DHT22 VCC → 3V3
- DHT22 DATA → GPIO 4
- DHT22 GND → GND
- LED + 220 Ω → GPIO 2 (DevKit V1 has one on the board)
Try: Click the DHT22 while the simulation runs and move the temperature slider.
Show the code
// Lab 1 - First ESP32: blink an LED and read temperature & humidity (DHT22)
// Board: ESP32 DevKit V1 (30-pin) or Wokwi ESP32 DevKitC. Serial Monitor: 115200.
// Library: "DHT sensor library for ESPx" (by beegee_tokyo)
//
// Wiring
// DHT22 VCC -> 3V3
// DHT22 DATA -> GPIO 4
// DHT22 GND -> GND
// LED (+ 220 ohm resistor) -> GPIO 2 (the DevKit V1 also has an on-board LED on GPIO 2)
#include "DHTesp.h"
const int DHT_PIN = 4;
const int LED_PIN = 2;
DHTesp dht;
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
dht.setup(DHT_PIN, DHTesp::DHT22); // use DHTesp::DHT11 if you have a DHT11
Serial.println("Lab 1: DHT22 ready");
}
void loop() {
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // blink once per reading
TempAndHumidity d = dht.getTempAndHumidity();
if (dht.getStatus() != 0) {
Serial.println(String("Sensor read failed: ") + dht.getStatusString());
} else {
Serial.printf("Temp %.1f C Humidity %.1f %%\n", d.temperature, d.humidity);
}
delay(2000); // DHT22 needs at least 2 s between readings
}
{
"version": 1,
"author": "Agri Sensors and Controls",
"editor": "wokwi",
"parts": [
{ "type": "board-esp32-devkit-c-v4", "id": "esp", "top": 0, "left": 0, "attrs": {} },
{ "type": "wokwi-dht22", "id": "dht1", "top": -76.5, "left": 168, "attrs": { "temperature": "31", "humidity": "62" } },
{ "type": "wokwi-resistor", "id": "r1", "top": 186, "left": 172, "rotate": 90, "attrs": { "value": "220" } },
{ "type": "wokwi-led", "id": "led1", "top": 250, "left": 180, "attrs": { "color": "green" } }
],
"connections": [
[ "esp:TX", "$serialMonitor:RX", "", [] ],
[ "esp:RX", "$serialMonitor:TX", "", [] ],
[ "dht1:VCC", "esp:3V3", "red", [] ],
[ "dht1:SDA", "esp:4", "green", [] ],
[ "dht1:GND", "esp:GND.2", "black", [] ],
[ "esp:2", "r1:1", "orange", [] ],
[ "r1:2", "led1:A", "orange", [] ],
[ "led1:C", "esp:GND.3", "black", [] ]
],
"dependencies": {}
}
Water flow meter (YF-S201)
Practicals 6, 10Count sensor pulses with an interrupt and turn them into L/min and litres.
Run it in Wokwi
- Open a new ESP32 project in Wokwi.
- Copy sketch.ino below and paste it over the code in the
sketch.inotab. - Copy diagram.json and paste it over the
diagram.jsontab. - Press the green ▶ button. The first run waits 20–40 s in Wokwi’s free build queue.
Wiring on a real board
- Red → 5V (VIN), Black → GND
- Yellow → 10 kΩ / 20 kΩ divider → GPIO 27 (5 V pulses, 3.3 V pin)
- Wokwi: the knob on GPIO 34 is the tap; GPIO 25 makes the pulses
Try: Turn the tap knob and watch L/min change. On a real board set SIMULATE_FLOW to 0.
Show the code
// Lab 2A - Water flow with a YF-S201 (pulses -> L/min and litres)
// YF-S201: pulse frequency (Hz) ~= 7.5 x flow (L/min), about 450 pulses per litre.
//
// Real hardware wiring
// Red -> 5V (VIN) Black -> GND
// Yellow (signal) -> 10k / 20k divider -> GPIO 27 (sensor gives 5 V pulses; ESP32 pins take 3.3 V)
// Set SIMULATE_FLOW to 0.
//
// Wokwi has no flow sensor, so with SIMULATE_FLOW 1 the knob on GPIO 34 is the "tap":
// the sketch makes matching pulses on GPIO 25, which is wired to GPIO 27.
#define SIMULATE_FLOW 1
const int FLOW_PIN = 27;
volatile uint32_t pulses = 0;
void IRAM_ATTR onPulse() { pulses++; } // runs on every pulse
float totalLitres = 0;
uint32_t lastMs = 0;
#if SIMULATE_FLOW
const int TAP_PIN = 34; // potentiometer = how far the tap is open
const int FAKE_PULSE_PIN = 25;
#endif
void setup() {
Serial.begin(115200);
pinMode(FLOW_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(FLOW_PIN), onPulse, FALLING);
#if SIMULATE_FLOW
pinMode(FAKE_PULSE_PIN, OUTPUT);
#endif
Serial.println("Lab 2A: flow meter ready");
}
void loop() {
#if SIMULATE_FLOW
// Make fake sensor pulses: toggle GPIO 25 at 7.5 x (L/min) Hz
static uint32_t lastToggleUs = 0, lastKnobMs = 0;
static float hz = 0;
if (millis() - lastKnobMs >= 200) { // read the tap knob 5x a second
lastKnobMs = millis();
float tapLpm = analogRead(TAP_PIN) * 30.0f / 4095.0f; // 0-30 L/min
hz = tapLpm * 7.5f;
}
if (hz >= 1 && micros() - lastToggleUs >= (uint32_t)(500000.0f / hz)) {
lastToggleUs = micros();
digitalWrite(FAKE_PULSE_PIN, !digitalRead(FAKE_PULSE_PIN));
}
#endif
if (millis() - lastMs >= 1000) { // once per second
noInterrupts();
uint32_t p = pulses;
pulses = 0;
interrupts();
float lpm = p / 7.5f; // pulses in 1 s = Hz
totalLitres += p / 450.0f;
Serial.printf("Flow %.2f L/min Total %.3f L\n", lpm, totalLitres);
lastMs = millis();
}
}
{
"version": 1,
"author": "Agri Sensors and Controls",
"editor": "wokwi",
"parts": [
{ "type": "board-esp32-devkit-c-v4", "id": "esp", "top": 0, "left": 0, "attrs": {} },
{ "type": "wokwi-potentiometer", "id": "tap", "top": -40, "left": -150, "attrs": { "value": "512" } },
{ "type": "wokwi-text", "id": "t1", "top": -70, "left": -160, "attrs": { "text": "Tap (flow)" } }
],
"connections": [
[ "esp:TX", "$serialMonitor:RX", "", [] ],
[ "esp:RX", "$serialMonitor:TX", "", [] ],
[ "tap:VCC", "esp:3V3", "red", [] ],
[ "tap:GND", "esp:GND.1", "black", [] ],
[ "tap:SIG", "esp:34", "green", [] ],
[ "esp:25", "esp:27", "blue", [ "h-24", "v19.2" ] ]
],
"dependencies": {}
}
Soil moisture + tank float + automatic pump
Practicals 6, 13Make decisions: water when dry, stop when wet, never run the pump with an empty tank.
Run it in Wokwi
- Open a new ESP32 project in Wokwi.
- Copy sketch.ino below and paste it over the code in the
sketch.inotab. - Copy diagram.json and paste it over the
diagram.jsontab. - Press the green ▶ button. The first run waits 20–40 s in Wokwi’s free build queue.
Wiring on a real board
- Soil sensor AOUT → GPIO 34 (Wokwi: knob)
- Float switch → GPIO 14 and GND (Wokwi: slide switch)
- Relay IN → GPIO 26, VCC → 5V, GND → GND
- Pump LED + 220 Ω → GPIO 26
Try: Turn the knob toward dry until the pump LED lights, then slide the float to EMPTY.
Show the code
// Lab 2B - Soil moisture + tank float switch + automatic pump
// Pump turns ON below 35 % moisture, OFF above 60 % (hysteresis stops relay chatter),
// and never runs when the tank float says EMPTY (safety interlock).
//
// Wiring
// Capacitive soil sensor AOUT -> GPIO 34 (Wokwi: the knob)
// Float switch -> GPIO 14 and GND (Wokwi: slide switch; left = tank has water)
// Relay module IN -> GPIO 26, VCC -> 5V (VIN), GND -> GND
// Pump LED (+ 220 ohm) -> GPIO 26 (use an LED or a small 5 V pump - no mains!)
//
// Use ADC1 pins (32-39) for analog: ADC2 pins stop working when WiFi is on.
// Many relay modules are active-LOW: if yours is, set RELAY_ACTIVE_HIGH to false.
const int SOIL_PIN = 34;
const int FLOAT_PIN = 14;
const int PUMP_PIN = 26;
const bool RELAY_ACTIVE_HIGH = true;
const int DRY = 3000; // raw reading in dry soil - calibrate with your sensor!
const int WET = 1300; // raw reading in water - calibrate with your sensor!
const int ON_BELOW = 35; // % moisture: start watering
const int OFF_ABOVE = 60; // % moisture: stop watering
bool pumpOn = false;
void setup() {
Serial.begin(115200);
pinMode(FLOAT_PIN, INPUT_PULLUP); // switch closed = LOW
pinMode(PUMP_PIN, OUTPUT);
Serial.println("Lab 2B: auto pump ready");
}
void loop() {
int raw = analogRead(SOIL_PIN);
int pct = constrain(map(raw, DRY, WET, 0, 100), 0, 100);
bool tankHasWater = (digitalRead(FLOAT_PIN) == LOW);
if (pct < ON_BELOW) pumpOn = true;
if (pct > OFF_ABOVE) pumpOn = false;
if (!tankHasWater) pumpOn = false; // safety interlock wins
digitalWrite(PUMP_PIN, (pumpOn == RELAY_ACTIVE_HIGH) ? HIGH : LOW);
Serial.printf("Soil %d%% (raw %d) Tank %s Pump %s\n",
pct, raw, tankHasWater ? "OK" : "EMPTY", pumpOn ? "ON" : "OFF");
delay(1000);
}
{
"version": 1,
"author": "Agri Sensors and Controls",
"editor": "wokwi",
"parts": [
{ "type": "board-esp32-devkit-c-v4", "id": "esp", "top": 0, "left": 0, "attrs": {} },
{ "type": "wokwi-potentiometer", "id": "soil", "top": -40, "left": -160, "attrs": { "value": "700" } },
{ "type": "wokwi-text", "id": "t1", "top": -70, "left": -170, "attrs": { "text": "Soil moisture" } },
{ "type": "wokwi-slide-switch", "id": "float", "top": 120, "left": -150, "attrs": { "value": "" } },
{ "type": "wokwi-text", "id": "t2", "top": 95, "left": -170, "attrs": { "text": "Tank float" } },
{ "type": "wokwi-relay-module", "id": "relay", "top": 20, "left": 200, "attrs": {} },
{ "type": "wokwi-resistor", "id": "r1", "top": 150, "left": 200, "attrs": { "value": "220" } },
{ "type": "wokwi-led", "id": "pump", "top": 110, "left": 300, "attrs": { "color": "blue" } },
{ "type": "wokwi-text", "id": "t3", "top": 80, "left": 290, "attrs": { "text": "Pump" } }
],
"connections": [
[ "esp:TX", "$serialMonitor:RX", "", [] ],
[ "esp:RX", "$serialMonitor:TX", "", [] ],
[ "soil:VCC", "esp:3V3", "red", [] ],
[ "soil:GND", "esp:GND.1", "black", [] ],
[ "soil:SIG", "esp:34", "green", [] ],
[ "float:2", "esp:14", "violet", [] ],
[ "float:1", "esp:GND.1", "black", [] ],
[ "relay:VCC", "esp:5V", "red", [] ],
[ "relay:GND", "esp:GND.2", "black", [] ],
[ "relay:IN", "esp:26", "orange", [] ],
[ "esp:26", "r1:1", "orange", [] ],
[ "r1:2", "pump:A", "orange", [] ],
[ "pump:C", "esp:GND.3", "black", [] ]
],
"dependencies": {}
}
Send readings to the cloud (ThingSpeak)
Practicals 10, 11 · Unit 4Connect to WiFi, call a web API and see live charts on your phone.
Run it in Wokwi
- Open a new ESP32 project in Wokwi.
- Copy sketch.ino below and paste it over the code in the
sketch.inotab. - Copy diagram.json and paste it over the
diagram.jsontab. - Library Manager tab → + → add DHT sensor library for ESPx.
- Press the green ▶ button. The first run waits 20–40 s in Wokwi’s free build queue.
Wiring on a real board
- Same as Lab 1 + soil sensor on GPIO 34
- Wokwi WiFi: Wokwi-GUEST, no password
- Real board: workshop router, 2.4 GHz, no login page
Try: Paste your ThingSpeak Write API Key, run it and open your channel on your phone.
Show the code
// Lab 3 - Send readings to the cloud (ThingSpeak) and see live charts
// 1. Sign up at thingspeak.mathworks.com -> New Channel -> enable Field 1 (Temp),
// Field 2 (Humidity), Field 3 (Soil %). API Keys tab -> copy the Write API Key below.
// 2. In Wokwi keep WIFI_SSID "Wokwi-GUEST" (no password). On a real board use the
// workshop router or a phone hotspot: 2.4 GHz and no login page.
// 3. Free ThingSpeak accounts accept one update every 15 s; we send every 20 s.
//
// Wiring: DHT22 DATA -> GPIO 4 (VCC 3V3, GND GND), soil sensor AOUT -> GPIO 34
// Library: "DHT sensor library for ESPx"
#include <WiFi.h>
#include <HTTPClient.h>
#include "DHTesp.h"
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASS = "";
const char* TS_KEY = "YOUR_WRITE_API_KEY";
const int DHT_PIN = 4;
const int SOIL_PIN = 34;
const int DRY = 3000, WET = 1300; // calibrate for your soil sensor
DHTesp dht;
void setup() {
Serial.begin(115200);
dht.setup(DHT_PIN, DHTesp::DHT22);
Serial.print("Connecting to WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println("\nWiFi connected, IP " + WiFi.localIP().toString());
}
void loop() {
TempAndHumidity d = dht.getTempAndHumidity();
int soil = constrain(map(analogRead(SOIL_PIN), DRY, WET, 0, 100), 0, 100);
if (dht.getStatus() == 0 && WiFi.status() == WL_CONNECTED) {
String url = String("http://api.thingspeak.com/update?api_key=") + TS_KEY
+ "&field1=" + String(d.temperature, 1)
+ "&field2=" + String(d.humidity, 1)
+ "&field3=" + soil;
HTTPClient http;
http.begin(url);
int code = http.GET(); // 200 and an entry number > 0 = success
Serial.printf("Temp %.1f C Hum %.1f %% Soil %d%% -> ThingSpeak HTTP %d, entry %s\n",
d.temperature, d.humidity, soil, code, http.getString().c_str());
http.end();
} else {
Serial.println("Skipped: sensor read failed or WiFi down");
}
delay(20000);
}
{
"version": 1,
"author": "Agri Sensors and Controls",
"editor": "wokwi",
"parts": [
{ "type": "board-esp32-devkit-c-v4", "id": "esp", "top": 0, "left": 0, "attrs": {} },
{ "type": "wokwi-dht22", "id": "dht1", "top": -76.5, "left": 168, "attrs": { "temperature": "31", "humidity": "62" } },
{ "type": "wokwi-potentiometer", "id": "soil", "top": -40, "left": -160, "attrs": { "value": "512" } },
{ "type": "wokwi-text", "id": "t1", "top": -70, "left": -170, "attrs": { "text": "Soil moisture" } }
],
"connections": [
[ "esp:TX", "$serialMonitor:RX", "", [] ],
[ "esp:RX", "$serialMonitor:TX", "", [] ],
[ "dht1:VCC", "esp:3V3", "red", [] ],
[ "dht1:SDA", "esp:4", "green", [] ],
[ "dht1:GND", "esp:GND.2", "black", [] ],
[ "soil:VCC", "esp:3V3", "red", [] ],
[ "soil:GND", "esp:GND.1", "black", [] ],
[ "soil:SIG", "esp:34", "green", [] ]
],
"dependencies": {}
}
A phone dashboard, built with AI
Unit 4 · Smartphone appsAsk an AI assistant (Claude, ChatGPT or Gemini) to write a web dashboard that your ESP32 serves over its own WiFi. Your job is to give it exact details, test what it writes, and paste errors back until it works. This lab needs a real board: a phone cannot join a simulated ESP32’s WiFi.
The loop
- Describe the board, pins, sensors and goal
- Generate code, wiring and an explanation
- Compile it (or paste it into Wokwi to check it builds)
- Flash the real board
- Paste back the exact error or Serial output
- Understand: ask about any line you can’t explain
Then
- Join WiFi
FarmNode-01from your phone and open192.168.4.1 - Ask for one new feature at a time: an Auto mode, a threshold slider, a buzzer alarm
- Never use AI advice to wire 230 V mains. That is work for a licensed electrician
The prompt
I am an agriculture student using an ESP32 DevKit V1 (30-pin) with Arduino IDE 2 and the Espressif ESP32 board package. Connected: - DHT22 temperature/humidity sensor on GPIO 4 - Capacitive soil moisture sensor on GPIO 34 (raw ~3000 dry, ~1300 wet) - Relay module for a small pump on GPIO 26 (active HIGH) Write one Arduino sketch that: 1. Starts a WiFi access point named "FarmNode-01" with password "farm12345" 2. Serves a mobile-friendly web page at 192.168.4.1 showing temperature, humidity and soil moisture %, refreshing every 2 seconds without reloading the page 3. Has a big Pump ON / Pump OFF button that switches the relay and shows the current state 4. Uses only the built-in WebServer library, plus "DHT sensor library for ESPx" for the DHT22 Then give me the wiring as a list, and explain the code section by section in simple language.
Stuck? Show a working reference solution
// Lab 4 - Reference solution: phone dashboard served by the ESP32 itself
// Students should generate their own version with an AI assistant using the Lab 4 prompt;
// this file is the facilitators' fallback and answer key.
//
// The ESP32 starts its own WiFi "FarmNode-01" (password farm12345). Join it from a phone
// and open http://192.168.4.1 -> live temp, humidity, soil %, and Pump ON/OFF/AUTO.
// Real hardware only: Wokwi cannot let a phone join a simulated access point.
//
// Wiring: DHT22 DATA -> GPIO 4, soil sensor AOUT -> GPIO 34, relay IN -> GPIO 26 (active HIGH)
// Library: "DHT sensor library for ESPx". WebServer is built into the ESP32 core.
#include <WiFi.h>
#include <WebServer.h>
#include "DHTesp.h"
const char* AP_SSID = "FarmNode-01";
const char* AP_PASS = "farm12345"; // at least 8 characters
const int DHT_PIN = 4, SOIL_PIN = 34, PUMP_PIN = 26;
const int DRY = 3000, WET = 1300;
const int ON_BELOW = 35, OFF_ABOVE = 60;
DHTesp dht;
WebServer server(80);
float tempC = NAN, humidity = NAN;
int soilPct = 0;
bool pumpOn = false;
bool autoMode = false;
const char PAGE[] PROGMEM = R"HTML(
<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>FarmNode-01</title>
<style>
body{font-family:system-ui,sans-serif;margin:0;padding:16px;background:#f3f6f1;color:#17231c}
h1{font-size:22px;margin:0 0 12px}
.grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px}
.card{background:#fff;border:1px solid #cbd6cc;border-radius:12px;padding:12px;text-align:center}
.v{font-size:28px;font-weight:700}.l{font-size:13px;color:#4a5a50}
.pump{margin-top:16px;padding:16px;border-radius:12px;background:#fff;border:1px solid #cbd6cc}
button{font-size:18px;padding:14px;border-radius:10px;border:0;width:32%;color:#fff}
.on{background:#0e5e43}.off{background:#9b2c1f}.auto{background:#2466a8}
#state{font-size:20px;font-weight:700;margin-bottom:10px}
</style></head><body>
<h1>FarmNode-01</h1>
<div class="grid">
<div class="card"><div class="v" id="t">--</div><div class="l">Temp °C</div></div>
<div class="card"><div class="v" id="h">--</div><div class="l">Humidity %</div></div>
<div class="card"><div class="v" id="s">--</div><div class="l">Soil %</div></div>
</div>
<div class="pump"><div id="state">Pump: --</div>
<button class="on" onclick="cmd('on')">ON</button>
<button class="off" onclick="cmd('off')">OFF</button>
<button class="auto" onclick="cmd('auto')">AUTO</button>
</div>
<script>
function show(d){
document.getElementById('t').textContent=d.temp;
document.getElementById('h').textContent=d.hum;
document.getElementById('s').textContent=d.soil;
document.getElementById('state').textContent='Pump: '+(d.pump?'ON':'OFF')+(d.auto?' (auto)':' (manual)');
}
function refresh(){fetch('/data').then(r=>r.json()).then(show).catch(()=>{});}
function cmd(c){fetch('/pump?set='+c).then(r=>r.json()).then(show);}
setInterval(refresh,2000);refresh();
</script></body></html>
)HTML";
void applyPump() { digitalWrite(PUMP_PIN, pumpOn ? HIGH : LOW); }
String json() {
return String("{\"temp\":\"") + (isnan(tempC) ? "--" : String(tempC, 1)) +
"\",\"hum\":\"" + (isnan(humidity) ? "--" : String(humidity, 0)) +
"\",\"soil\":" + soilPct +
",\"pump\":" + (pumpOn ? "true" : "false") +
",\"auto\":" + (autoMode ? "true" : "false") + "}";
}
void handleRoot() { server.send_P(200, "text/html", PAGE); }
void handleData() { server.send(200, "application/json", json()); }
void handlePump() {
String set = server.arg("set");
if (set == "on") { autoMode = false; pumpOn = true; }
if (set == "off") { autoMode = false; pumpOn = false; }
if (set == "auto") { autoMode = true; }
applyPump();
server.send(200, "application/json", json());
}
void setup() {
Serial.begin(115200);
pinMode(PUMP_PIN, OUTPUT);
applyPump();
dht.setup(DHT_PIN, DHTesp::DHT22);
WiFi.softAP(AP_SSID, AP_PASS);
Serial.println("Join WiFi " + String(AP_SSID) + " and open http://" + WiFi.softAPIP().toString());
server.on("/", handleRoot);
server.on("/data", handleData);
server.on("/pump", handlePump);
server.begin();
}
uint32_t lastRead = 0;
void loop() {
server.handleClient();
if (millis() - lastRead >= 2000) {
lastRead = millis();
TempAndHumidity d = dht.getTempAndHumidity();
if (dht.getStatus() == 0) { tempC = d.temperature; humidity = d.humidity; }
soilPct = constrain(map(analogRead(SOIL_PIN), DRY, WET, 0, 100), 0, 100);
if (autoMode) {
if (soilPct < ON_BELOW) pumpOn = true;
if (soilPct > OFF_ABOVE) pumpOn = false;
applyPump();
}
}
}
Keep learning
- NPTEL: Introduction to Internet of Things · IIT Kharagpur, free
- Random Nerd Tutorials: ESP32 projects · step-by-step guides for every sensor
- Wokwi documentation · every simulated part and how to use it
- ThingSpeak · free cloud charts for Lab 3
- KiCad · free PCB design, when you are ready for your own board