PCINT Review → ESP-01 Hardware → AT Commands → Mini Projects
Quick warm-up exercises on pin change interrupts from last week
Hardware overview, pinout, wiring to Arduino Uno
Communicating with the ESP-01 via serial AT commands
Choose your project: WiFi Walkie-Talkie or Phone Control Panel (no extra parts!)
| Group | Port | Pins | Vector | PCICR Bit | Mask |
|---|---|---|---|---|---|
| 0 | B | D8–D13 | PCINT0_vect | PCIE0 | PCMSK0 |
| 1 | C | A0–A5 | PCINT1_vect | PCIE1 | PCMSK1 |
| 2 | D | D0–D7 | PCINT2_vect | PCIE2 | PCMSK2 |
// Generic PCINT setup pattern:
// 1. Enable group in PCICR
PCICR |= (1 << PCIEx);
// 2. Enable specific pin in mask
PCMSKx |= (1 << PCINTn);
// 3. Write the ISR
ISR(PCINTx_vect) {
// Check which pin changed
if (PIND & (1 << PDn)) {
// Rising edge (pin went HIGH)
} else {
// Falling edge (pin went LOW)
}
}
// 4. Enable global interrupts
sei();
You want a pin change interrupt on analog pin A2. Fill in each blank:
Configure a pin change interrupt on digital pin D10. Fill in each blank:
Configure a pin change interrupt on digital pin D4. Fill in each blank:
| Chip | ESP8266EX |
| WiFi | 802.11 b/g/n |
| Voltage | 3.3V |
| Current (peak) | ~170 mA |
| Flash | 1 MB |
| GPIO Pins | 2 (GPIO0, GPIO2) |
| UART | TX, RX |
| Baud Rate | 9600 or 115200 (varies) |
| Pin | Name | Function |
|---|---|---|
| 1 | VCC | 3.3V power supply |
| 2 | GND | Ground |
| 3 | TX | Transmit data (to Arduino RX) |
| 4 | RX | Receive data (from Arduino TX) |
| 5 | RST | Reset (active LOW) |
| 6 | CH_PD / EN | Chip enable (pull HIGH) |
| 7 | GPIO0 | General purpose I/O |
| 8 | GPIO2 | General purpose I/O |
| ESP-01 Pin | → | Arduino / Power | Notes |
|---|---|---|---|
| VCC | → | 3.3V | Use Arduino 3.3V output |
| GND | → | GND | Common ground |
| TX | → | Pin 2 (SoftwareSerial RX) | Direct connection OK |
| RX | → | Pin 3 via voltage divider | 5V → 3.3V needed! |
| CH_PD / EN | → | 3.3V | Must be HIGH to run |
| RST | → | (leave unconnected or 3.3V) | Optional |
| GPIO0 | → | (leave unconnected) | HIGH = normal mode |
| GPIO2 | → | (leave unconnected) | Must be HIGH at boot |
Arduino Uno R3 TX is 5V but ESP-01 RX only accepts 3.3V. Use a resistor divider (1kΩ + 2kΩ):
V_out = 5V × 2kΩ / (1kΩ + 2kΩ) = 3.3V
SoftwareSerial library creates a second serial port.
SoftwareSerial is a built-in library that ships with the Arduino IDE. You do not need to install it from the Library Manager. Simply write #include <SoftwareSerial.h> at the top of your sketch and it's ready to use.
Upload this sketch to verify your ESP-01 is responding:
AT and press EnterAT → OK#include <SoftwareSerial.h>
// ESP-01: TX → Pin 2, RX → Pin 3
SoftwareSerial esp(2, 3);
void setup() {
Serial.begin(9600); // USB serial
esp.begin(9600); // ESP-01 baud rate
Serial.println("ESP-01 Test Ready");
Serial.println("Type AT commands:");
}
void loop() {
// Forward: Serial Monitor → ESP-01
if (Serial.available()) {
esp.write(Serial.read());
}
// Forward: ESP-01 → Serial Monitor
if (esp.available()) {
Serial.write(esp.read());
}
}
Some ESP-01 modules ship with 9600 baud as default, while others come set to 115200. If you use the wrong baud rate, you'll get garbage characters in the Serial Monitor.
| Serial Monitor Output | Meaning |
|---|---|
ESP responding at 9600 | Already at 9600 ✅ — you're good! |
ESP responding at 115200 | Needs to be changed → next slide |
No response at either rate | Check wiring & CH_PD |
SoftwareSerial on Arduino is unreliable at 115200 — it drops characters and corrupts data. At 9600 baud, it works perfectly with AT commands.
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3);
void setup() {
Serial.begin(9600);
Serial.println("=== ESP Baud Rate Detector ===");
Serial.println();
// Try 9600 first
Serial.print("Trying 9600... ");
esp.begin(9600);
delay(1000);
esp.println("AT");
delay(1000);
if (esp.find("OK")) {
Serial.println("ESP responding at 9600");
Serial.println("You're all set!");
return;
}
// Try 115200
Serial.print("Trying 115200...");
esp.begin(115200);
delay(1000);
esp.println("AT");
delay(1000);
if (esp.find("OK")) {
Serial.println("ESP responding at 115200");
Serial.println(">> Change it to 9600!");
Serial.println(">> See next slide.");
return;
}
Serial.println();
Serial.println("No response at either rate.");
Serial.println("Check your wiring!");
}
void loop() { }
If your ESP is at 115200, use this sketch to permanently change it to 9600:
| Parameter | Value | Meaning |
|---|---|---|
| Baud rate | 9600 | New speed |
| Data bits | 8 | Standard |
| Stop bits | 1 | Standard |
| Parity | 0 | None |
| Flow control | 0 | Disabled |
esp.begin(9600) in all your sketches.
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3);
void setup() {
Serial.begin(9600);
Serial.println("=== Change ESP to 9600 ===");
Serial.println();
// Connect at current speed (115200)
esp.begin(115200);
delay(1000);
// Send the baud rate change command
Serial.println("Sending AT+UART_DEF=9600...");
esp.println("AT+UART_DEF=9600,8,1,0,0");
delay(2000);
// Now reconnect at 9600 to verify
esp.begin(9600);
delay(1000);
// Test with AT
esp.println("AT");
delay(1000);
String response = "";
while (esp.available()) {
response += (char)esp.read();
}
Serial.println("Response: " + response);
if (response.indexOf("OK") != -1) {
Serial.println();
Serial.println("Baud rate changed to 9600!");
Serial.println("You're all set!");
} else {
Serial.println("Something went wrong.");
Serial.println("Try uploading again.");
}
}
void loop() { }
| Command | Description | Example Response |
|---|---|---|
AT | Test connection | OK |
AT+RST | Reset module | ready |
AT+GMR | Firmware version | AT version: ... |
AT+CWMODE=1 | Set Station mode | OK |
AT+CWMODE=2 | Set AP mode | OK |
AT+CWMODE=3 | Set Station + AP | OK |
AT+CWJAP="ssid","pass" | Connect to WiFi | WIFI CONNECTED |
AT+CIFSR | Get IP address | +CIFSR:STAIP,"..." |
AT+CIPMUX=1 | Enable multiple connections | OK |
AT+CIPSERVER=1,80 | Start TCP server on port 80 | OK |
\r\n (carriage return + newline)Try typing AT commands below. The simulator responds like a real ESP-01:
192.168.1.42. Other devices on the same network can communicate with it.
Before connecting your ESP-01, you need to know the exact SSID (network name) and password of the NZSE Wi-Fi. Here's how to find it:
AT+CWLAP via Serial Monitor. The ESP will list all visible networks:
The format is: (encryption, "SSID", signal_strength, ...)
"NZSE-Student" is different from "nzse-student"netsh wlan show profile name="SSID" key=clear (Windows CMD)Writing AT command code gets repetitive. This helper function sends a command and waits for a response:
sendATCommand("AT+CWMODE=2", 1000);sendATCommand("AT+CWSAP=...", 3000);timeout ms, and prints the ESP's response to Serial Monitor.
String sendATCommand(String cmd, int timeout) {
String response = "";
esp.println(cmd); // Send command to ESP
long int time = millis();
while ((millis() - time) < timeout) {
while (esp.available()) {
char c = esp.read();
response += c;
}
}
Serial.println(response); // Debug output
return response;
}
// Example usage in setup():
void setup() {
Serial.begin(9600);
esp.begin(9600);
sendATCommand("AT", 1000);
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"MyESP\","
"\"12345678\",5,3", 3000);
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,80", 1000);
sendATCommand("AT+CIFSR", 1000);
}
Replace YOUR_SSID and YOUR_PASSWORD with the actual values from the previous slide:
FAIL → Wrong SSID or passwordDISCONNECT → Out of range or network fullAT+RST)#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3);
// ====== CHANGE THESE ======
String ssid = "YOUR_SSID"; // e.g. "NZSE-Student"
String password = "YOUR_PASSWORD"; // ask instructor
// ==========================
void setup() {
Serial.begin(9600);
esp.begin(9600);
delay(2000);
Serial.println("Connecting to NZSE Wi-Fi...");
// 1. Station mode
sendATCommand("AT+CWMODE=1", 2000);
// 2. Connect to the network
String joinCmd = "AT+CWJAP=\"" + ssid + "\",\""
+ password + "\"";
String resp = sendATCommand(joinCmd, 10000);
if (resp.indexOf("OK") != -1) {
Serial.println("=== WiFi Connected! ===");
// 3. Show assigned IP
sendATCommand("AT+CIFSR", 2000);
} else {
Serial.println("Connection failed!");
Serial.println(resp);
}
}
void loop() {
// pass-through for debugging
if (esp.available()) Serial.write(esp.read());
if (Serial.available()) esp.write(Serial.read());
}
Once connected to NZSE Wi-Fi, verify the connection actually works by fetching a real web page. We'll request example.com:
HTTP/1.1 200 OK — you are connected to the internet through NZSE Wi-Fi!
This sketch connects to NZSE Wi-Fi and then fetches a page from example.com to prove internet connectivity:
AT+CIPSEND needs the exact number of bytes. Our request string is:
GET / HTTP/1.1\r\n
Host: example.com\r\n
\r\n
That's 18 + 21 + 4 = 43 bytes (counting each \r\n as 2 bytes).
Connecting to WiFi...=== WiFi Connected! ===Fetching example.com...HTTP/1.1 200 OK...<h1>Example Domain</h1>...
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3);
String ssid = "YOUR_SSID";
String password = "YOUR_PASSWORD";
void setup() {
Serial.begin(9600);
esp.begin(9600);
delay(2000);
// Connect to Wi-Fi
sendATCommand("AT+CWMODE=1", 2000);
String join = "AT+CWJAP=\"" + ssid + "\",\""
+ password + "\"";
String r = sendATCommand(join, 10000);
if (r.indexOf("OK") == -1) {
Serial.println("WiFi FAILED"); return;
}
Serial.println("=== WiFi Connected! ===");
sendATCommand("AT+CIFSR", 2000);
// Open TCP connection to example.com
Serial.println("Fetching example.com...");
sendATCommand(
"AT+CIPSTART=\"TCP\",\"example.com\",80",
5000);
// HTTP GET request (43 bytes)
String http = "GET / HTTP/1.1\r\n"
"Host: example.com\r\n\r\n";
sendATCommand("AT+CIPSEND=" +
String(http.length()), 2000);
sendATCommand(http, 5000);
}
void loop() {
if (esp.available()) Serial.write(esp.read());
}
Today your Arduino becomes a tiny website. A phone will ask it for a page, and it will answer.
🖐 By hand = type AT commands yourself 💻 In code = the Arduino types them
Every slide tells you in a bar at the top:
Uploading resets only the Arduino, not the ESP, so anything you set up by hand keeps running.
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3); // ESP TX → D2, ESP RX → D3
void setup() {
Serial.begin(9600);
esp.begin(9600);
}
void loop() {
if (Serial.available()) esp.write(Serial.read()); // you type → ESP
if (esp.available()) Serial.write(esp.read()); // ESP reply → you
}AT+CWMODE=2 become a hotspotAT+CWSAP="ESP_Reza","12345678",5,3AT+CIFSR its address is always 192.168.4.1MyESP is chaos), and turn off mobile data so your phone doesn't escape back to 4G.
Now let the Arduino type those 3 commands for you, every time it starts.
sendATCommand(): our helper from slide 20loop(): the slide 12 passthrough, so you can still watch everything and type extra commandsOKs and the IP address, and your hotspot appears on the phone.
Change ESP_Reza to your own name before uploading.
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3); // ESP TX → D2, ESP RX → D3
// Helper from slide 20: send a command, print the reply
String sendATCommand(String cmd, int timeout) {
String response = "";
esp.println(cmd);
long start = millis();
while (millis() - start < timeout) {
while (esp.available()) response += (char)esp.read();
}
Serial.print(response);
return response;
}
void setup() {
Serial.begin(9600);
esp.begin(9600);
pinMode(13, OUTPUT); // built-in "L" LED
delay(2000); // let the ESP boot
// ── STEP 1: make the hotspot ──
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"ESP_Reza\",\"12345678\",5,3", 2000);
sendATCommand("AT+CIFSR", 1000);
}
void loop() {
// Two-way passthrough (slide 12): watch the ESP, type commands
if (esp.available()) Serial.write(esp.read());
if (Serial.available()) esp.write(Serial.read());
}
loop() is the passthrough, so you can type commands.The phone can join the hotspot, but nobody is listening yet. Two commands start a web server:
AT+CIPMUX=1 allow several visitors at onceAT+CIPSERVER=1,80 1 = start server, 80 = the web portCIPMUX=1, or CIPSERVER gives ERROR.)
Add the two commands to setup(). loop() is still the passthrough, so you see everything the ESP says.
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3); // ESP TX → D2, ESP RX → D3
// Helper from slide 20: send a command, print the reply
String sendATCommand(String cmd, int timeout) {
String response = "";
esp.println(cmd);
long start = millis();
while (millis() - start < timeout) {
while (esp.available()) response += (char)esp.read();
}
Serial.print(response);
return response;
}
void setup() {
Serial.begin(9600);
esp.begin(9600);
pinMode(13, OUTPUT); // built-in "L" LED
delay(2000); // let the ESP boot
// ── STEP 1: make the hotspot ──
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"ESP_Reza\",\"12345678\",5,3", 2000);
sendATCommand("AT+CIFSR", 1000);
// ── STEP 2: open the door (server on port 80) ──
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,80", 1000);
Serial.println("Ready! Browse to http://192.168.4.1");
}
void loop() {
// Two-way passthrough (slide 12): watch the ESP, type commands
if (esp.available()) Serial.write(esp.read());
if (Serial.available()) esp.write(Serial.read());
}
Look at the line that just appeared. Every incoming message starts with +IPD and has 4 parts:
Only the first line matters to us. The part between GET and HTTP is the path, i.e. what they want:
| Phone opens | First line of the request |
|---|---|
192.168.4.1 | GET / HTTP/1.1 |
192.168.4.1/led/on | GET /led/on HTTP/1.1 |
192.168.4.1/hello. Find /hello in the Serial Monitor. Does the connection ID change?
While the phone is still spinning, you reply. It's a 3-move handshake:
AT+CIPSEND=0,7> "OK, go ahead"Hello + EnterSEND OKAT+CIPCLOSE=00,CLOSED\r\n (that's what "Both NL & CR" means).
| Data | Bytes | Command |
|---|---|---|
Hi + Enter | 4 | AT+CIPSEND=0,4 |
Hello + Enter | 7 | AT+CIPSEND=0,7 |
<h1>Hi</h1> + Enter | 13 | AT+CIPSEND=0,13 |
ERROR. Too few → the ESP waits for the rest.
/favicon.ico: ignore it.
The passthrough has done its job. Now loop() does what your eyes did in Step 3. Each esp. call eats characters from the front: grey = eaten, yellow = what it returns.
esp.find("+IPD,") → true
esp.parseInt() → 0
esp.find(":") → true
readStringUntil('\n') → "GET / HTTP/1.1"
skipRest() → buffer empty, ready for the next visitorClient 0 asked for: GET / HTTP/1.1. Still spinning: we read, but don't answer yet.
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3); // ESP TX → D2, ESP RX → D3
// Helper from slide 20: send a command, print the reply
String sendATCommand(String cmd, int timeout) {
String response = "";
esp.println(cmd);
long start = millis();
while (millis() - start < timeout) {
while (esp.available()) response += (char)esp.read();
}
Serial.print(response);
return response;
}
// Throw away the rest of the request (keep reading until the ESP is quiet)
void skipRest() {
long t = millis();
while (millis() - t < 100) {
if (esp.available()) { esp.read(); t = millis(); }
}
}
void setup() {
Serial.begin(9600);
esp.begin(9600);
pinMode(13, OUTPUT); // built-in "L" LED
delay(2000); // let the ESP boot
// ── STEP 1: make the hotspot ──
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"ESP_Reza\",\"12345678\",5,3", 2000);
sendATCommand("AT+CIFSR", 1000);
// ── STEP 2: open the door (server on port 80) ──
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,80", 1000);
Serial.println("Ready! Browse to http://192.168.4.1");
}
void loop() {
// ── STEP 5a: read the request (what you did by eye in Step 3) ──
if (esp.available() && esp.find("+IPD,")) { // ① wait for "+IPD,"
int connId = esp.parseInt(); // ② who is asking? (0, 1...)
esp.find(":"); // ③ skip ",398:"
String request = esp.readStringUntil('\n'); // ④ "GET / HTTP/1.1"
skipRest(); // ⑤ ignore the headers
Serial.println("Client " + String(connId) + " asked for: " + request);
}
}
sendResponse() does exactly what you typed in Step 4, plus an HTTP envelope:
| Step 4 (by hand) | sendResponse() |
|---|---|
| — | ① build the header |
AT+CIPSEND=0,7 | ② count bytes, send CIPSEND |
wait for > | ③ wait for > |
Hello | ④ print header + page |
AT+CIPCLOSE=0 | ⑤ close |
print, not println: println would add 2 bytes we didn't count!
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3); // ESP TX → D2, ESP RX → D3
// Helper from slide 20: send a command, print the reply
String sendATCommand(String cmd, int timeout) {
String response = "";
esp.println(cmd);
long start = millis();
while (millis() - start < timeout) {
while (esp.available()) response += (char)esp.read();
}
Serial.print(response);
return response;
}
// Throw away the rest of the request (keep reading until the ESP is quiet)
void skipRest() {
long t = millis();
while (millis() - t < 100) {
if (esp.available()) { esp.read(); t = millis(); }
}
}
// Do Step 4 for us: CIPSEND, wait for ">", send, CIPCLOSE
void sendResponse(int connId, const String &content) {
// ① The "envelope" every browser expects first
String header = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n\r\n";
// ② Tell the ESP how many bytes are coming
int len = header.length() + content.length();
esp.println("AT+CIPSEND=" + String(connId) + "," + String(len));
// ③ Wait (max 2 s) for ">" = "go ahead"
long start = millis();
while (millis() - start < 2000) {
if (esp.available() && esp.read() == '>') break;
}
// ④ Send envelope + page (print, NOT println!)
esp.print(header);
esp.print(content);
delay(500); // let the ESP finish sending
// ⑤ Hang up
esp.println("AT+CIPCLOSE=" + String(connId));
delay(300);
}
void setup() {
Serial.begin(9600);
esp.begin(9600);
pinMode(13, OUTPUT); // built-in "L" LED
delay(2000); // let the ESP boot
// ── STEP 1: make the hotspot ──
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"ESP_Reza\",\"12345678\",5,3", 2000);
sendATCommand("AT+CIFSR", 1000);
// ── STEP 2: open the door (server on port 80) ──
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,80", 1000);
Serial.println("Ready! Browse to http://192.168.4.1");
}
void loop() {
// ── STEP 5a: read the request (what you did by eye in Step 3) ──
if (esp.available() && esp.find("+IPD,")) { // ① wait for "+IPD,"
int connId = esp.parseInt(); // ② who is asking? (0, 1...)
esp.find(":"); // ③ skip ",398:"
String request = esp.readStringUntil('\n'); // ④ "GET / HTTP/1.1"
skipRest(); // ⑤ ignore the headers
Serial.println("Client " + String(connId) + " asked for: " + request);
// ── STEP 5b: answer (what you typed in Step 4) ──
sendResponse(connId, "Hello from ESP!");
}
}
We already have the request line. Now look inside it with indexOf():
indexOf("/led/on") returns where the text starts, or -1 if it isn't there:
!= -1 just means "found it".
192.168.4.1/led/on → "LED is ON" and the L LED lights 💡192.168.4.1/led/off → LED off192.168.4.1/anything → "Hello from ESP!"#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3); // ESP TX → D2, ESP RX → D3
// Helper from slide 20: send a command, print the reply
String sendATCommand(String cmd, int timeout) {
String response = "";
esp.println(cmd);
long start = millis();
while (millis() - start < timeout) {
while (esp.available()) response += (char)esp.read();
}
Serial.print(response);
return response;
}
// Throw away the rest of the request (keep reading until the ESP is quiet)
void skipRest() {
long t = millis();
while (millis() - t < 100) {
if (esp.available()) { esp.read(); t = millis(); }
}
}
// Do Step 4 for us: CIPSEND, wait for ">", send, CIPCLOSE
void sendResponse(int connId, const String &content) {
// ① The "envelope" every browser expects first
String header = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n\r\n";
// ② Tell the ESP how many bytes are coming
int len = header.length() + content.length();
esp.println("AT+CIPSEND=" + String(connId) + "," + String(len));
// ③ Wait (max 2 s) for ">" = "go ahead"
long start = millis();
while (millis() - start < 2000) {
if (esp.available() && esp.read() == '>') break;
}
// ④ Send envelope + page (print, NOT println!)
esp.print(header);
esp.print(content);
delay(500); // let the ESP finish sending
// ⑤ Hang up
esp.println("AT+CIPCLOSE=" + String(connId));
delay(300);
}
void setup() {
Serial.begin(9600);
esp.begin(9600);
pinMode(13, OUTPUT); // built-in "L" LED
delay(2000); // let the ESP boot
// ── STEP 1: make the hotspot ──
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"ESP_Reza\",\"12345678\",5,3", 2000);
sendATCommand("AT+CIFSR", 1000);
// ── STEP 2: open the door (server on port 80) ──
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,80", 1000);
Serial.println("Ready! Browse to http://192.168.4.1");
}
void loop() {
// ── STEP 5a: read the request (what you did by eye in Step 3) ──
if (esp.available() && esp.find("+IPD,")) { // ① wait for "+IPD,"
int connId = esp.parseInt(); // ② who is asking? (0, 1...)
esp.find(":"); // ③ skip ",398:"
String request = esp.readStringUntil('\n'); // ④ "GET / HTTP/1.1"
skipRest(); // ⑤ ignore the headers
Serial.println("Client " + String(connId) + " asked for: " + request);
// ── STEP 6: do what was asked ──
String reply = "Hello from ESP!";
if (request.indexOf("/led/on") != -1) {
digitalWrite(13, HIGH);
reply = "LED is ON";
}
if (request.indexOf("/led/off") != -1) {
digitalWrite(13, LOW);
reply = "LED is OFF";
}
// ── STEP 5b: answer (what you typed in Step 4) ──
sendResponse(connId, reply);
}
}
setup(), onceAT+CWMODE=2 · AT+CWSAP=...make the hotspotAT+CIPMUX=1 · AT+CIPSERVER=1,80open the doorloop(), every visit+IPD,0,398:GET /led/on HTTP/1.1the requestindexOf("/led/on") → LED ondecideAT+CIPSEND=0,len"len bytes coming">"go ahead"HTTP/1.1 200 OK ... LED is ONthe pageAT+CIPCLOSE=0hang up+IPD → decide → CIPSEND → data → CIPCLOSEsendATCommand() and sendResponse() are.
Pair up! One board makes a hotspot, the other joins it. Chat between two Serial Monitors, then use secret commands to take over your friend's LED: make it blink, flash Morse code, or measure your ping.
Build a mini web app on your phone: buttons for the LED, live chip temperature and uptime, and a Guess-My-Number game. Win and the board throws a light show!
| 📻 A: Walkie-Talkie | 📱 B: Control Panel | |
|---|---|---|
| Who talks | Arduino ⟷ Arduino | Phone → Arduino |
| WiFi | Board A = hotspot Board B joins it | Arduino = hotspot Phone joins it |
| You'll use | +IPD, CIPSEND, text commands | +IPD, sendResponse(), HTML forms |
| Coolest bit | Morse code on your friend's LED | Temperature with no sensor wired |
| Team | Pairs (2 boards) | Solo |
| Difficulty | ⭐⭐⭐ | ⭐⭐⭐ |
IS_HOST trueIS_HOST false✅ One sketch for both boards. Only IS_HOST changes. Using our own hotspot means no IP to look up and no school network to fight with.
ROOM name and PASSword togetherIS_HOST true to Board A, wait 10 sIS_HOST false to Board B, look for CONNECT| You type | What happens on your friend's board |
|---|---|
hello! | Shows Reza: hello! + quick LED flash 🔔 |
/blink 5 | LED blinks 5 times 💡 |
/morse SOS | LED flashes ... --- ... 📡 |
/ping | Replies /pong automatically. You see the round-trip time in ms ⏱ |
/morse word. First to read it wins!
Settings, helpers and setup().
IS_HOST: true on one board, false on the otherMY_NAME: your nicknameROOM + PASS: the same on both boardssendMsg() = CIPSEND to link 0, wait for >, then print"\n" so the other side knows where it stopsAT+CIPSTART=0,... so both boards talk on link 0. Same code works for both!// PROJECT A — WiFi WALKIE-TALKIE (Part 1 of 2)
// Same sketch on BOTH boards. Only IS_HOST changes.
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3);
// ========== CHANGE THESE ==========
#define IS_HOST true // Board A: true Board B: false
#define MY_NAME "Reza" // your nickname
#define ROOM "Chat_Reza" // hotspot name (same on both!)
#define PASS "12345678" // at least 8 characters
// ==================================
const int LED = 13; // built-in "L" LED
unsigned long pingStart = 0; // used to time /ping
String sendATCommand(String cmd, int t) {
String r = "";
esp.println(cmd);
long m = millis();
while (millis() - m < t) {
while (esp.available()) r += (char)esp.read();
}
Serial.println(r);
return r;
}
// Send one message to the other board (link 0)
void sendMsg(String msg) {
msg += "\n"; // "\n" marks the end of a message
esp.println("AT+CIPSEND=0," + String(msg.length()));
long start = millis(); // wait for ">"
while (millis() - start < 1000) {
if (esp.available() && esp.read() == '>') break;
}
esp.print(msg); // print, NOT println!
}
void setup() {
Serial.begin(9600);
esp.begin(9600);
esp.setTimeout(300); // find()/readString give up after 300 ms
pinMode(LED, OUTPUT);
delay(2000);
if (IS_HOST) { // Board A: make the hotspot + server
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"" ROOM "\",\"" PASS "\",5,3", 2000);
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,333", 1000);
} else { // Board B: join it + connect
sendATCommand("AT+CWMODE=1", 1000);
sendATCommand("AT+CWJAP=\"" ROOM "\",\"" PASS "\"", 8000);
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSTART=0,\"TCP\",\"192.168.4.1\",333", 3000);
}
Serial.println("--- Walkie-Talkie ready! ---");
Serial.println("Try: /blink 5 /morse SOS /ping");
}
loop() does two jobs: send what you type, and handle what arrives.
msg.substring(7).toInt(): "/blink 5" → skip 7 chars → 5MORSE[c - 'A']: 'C' - 'A' = 2 → the 3rd code. Letters are just numbers!/ping stores millis(), and /pong subtracts it/roll: both boards roll a dice with random(1,7). Highest wins/rps rock: rock-paper-scissors duel0–9 to the Morse table/speed 100: change the Morse dot length// PROJECT A — WiFi WALKIE-TALKIE (Part 2 of 2)
// Paste this BELOW Part 1 in the same sketch.
void loop() {
// 1. You typed something in Serial Monitor -> send it
if (Serial.available()) {
String msg = Serial.readStringUntil('\n');
msg.trim();
if (msg.startsWith("/")) { // a command: send as-is
if (msg == "/ping") pingStart = millis();
sendMsg(msg);
Serial.println("[sent " + msg + "]");
} else if (msg.length() > 0) { // chat: add your name
sendMsg(String(MY_NAME) + ": " + msg);
Serial.println("You: " + msg);
}
}
// 2. Your friend sent something -> +IPD,0,LEN:message
if (esp.available() && esp.find("+IPD,")) {
esp.find(":"); // skip "0,LEN:"
String msg = esp.readStringUntil('\n');
msg.trim();
handleMessage(msg);
}
}
void handleMessage(String msg) {
if (msg.startsWith("/blink")) { // "/blink 5" -> 5
int n = msg.substring(7).toInt();
if (n <= 0) n = 3;
Serial.println("Friend is blinking your LED " + String(n) + "x!");
for (int i = 0; i < n; i++) {
digitalWrite(LED, HIGH); delay(200);
digitalWrite(LED, LOW); delay(200);
}
}
else if (msg.startsWith("/morse")) { // "/morse SOS" -> "SOS"
String text = msg.substring(7);
Serial.print("Incoming Morse: ");
playMorse(text);
}
else if (msg == "/ping") {
sendMsg("/pong"); // answer automatically
}
else if (msg == "/pong") {
Serial.println("Pong! Round trip: " +
String(millis() - pingStart) + " ms");
}
else { // normal chat message
Serial.println(msg);
digitalWrite(LED, HIGH); delay(60); // "new message" flash
digitalWrite(LED, LOW);
}
}
// Morse code for A..Z (index 0 = 'A', 1 = 'B', ...)
const char* MORSE[] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
void playMorse(String text) {
text.toUpperCase();
for (unsigned int i = 0; i < text.length(); i++) {
char c = text[i];
if (c == ' ') { delay(700); continue; } // gap between words
if (c < 'A' || c > 'Z') continue; // letters only
const char* code = MORSE[c - 'A']; // 'C' - 'A' = 2
Serial.print(code); Serial.print(' ');
for (int j = 0; code[j] != '\0'; j++) {
digitalWrite(LED, HIGH);
delay(code[j] == '.' ? 150 : 450); // dot short, dash long
digitalWrite(LED, LOW);
delay(150);
}
delay(300); // gap between letters
}
Serial.println();
}
| You tap | Browser asks for | Arduino does |
|---|---|---|
| ON / OFF | GET /on · GET /off | Sets the LED |
| BLINK | GET /blink | Blinks 6 times |
| Guess "42" | GET /guess?n=42 | Too high / too low / 🎉 |
| 🔄 Refresh | GET / | Fresh temperature + uptime |
After every request, the Arduino builds the whole page again with the latest values and sends it with sendResponse().
Settings, helpers and setup().
MY_NAME → your hotspot becomes Panel_YourName
sendResponse() and skipRest() are the same helpers from slides 31 & 32readChipTemp() sets ADMUX/ADCSRA bits by hand, like the PCINT registersrandomSeed(analogRead(A0)): an unconnected pin reads random noise, so you get a new secret number each time// PROJECT B — PHONE CONTROL PANEL (Part 1 of 2)
// No extra parts: built-in LED + the chip's own temperature sensor
#include <SoftwareSerial.h>
SoftwareSerial esp(2, 3);
#define MY_NAME "Reza" // shown on the page + hotspot name
const int LED = 13; // built-in "L" LED
bool ledOn = false;
int views = 0; // page views
int secret, tries = 0; // guessing game
String gameMsg = "I'm thinking of a number 1-100...";
String sendATCommand(String cmd, int t) {
String r = "";
esp.println(cmd);
long m = millis();
while (millis() - m < t) {
while (esp.available()) r += (char)esp.read();
}
Serial.println(r);
return r;
}
// Same helper as slide 32
void sendResponse(int connId, const String &content) {
// ① The "envelope" every browser expects first
String header = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Connection: close\r\n\r\n";
// ② Tell the ESP how many bytes are coming
int len = header.length() + content.length();
esp.println("AT+CIPSEND=" + String(connId) + "," + String(len));
// ③ Wait (max 2 s) for ">" = "go ahead"
long start = millis();
while (millis() - start < 2000) {
if (esp.available() && esp.read() == '>') break;
}
// ④ Send envelope + page (print, NOT println!)
esp.print(header);
esp.print(content);
delay(500); // let the ESP finish sending
// ⑤ Hang up
esp.println("AT+CIPCLOSE=" + String(connId));
delay(300);
}
// Same helper as slide 31
// Keep reading until the ESP is quiet for 100 ms
void skipRest() {
long t = millis();
while (millis() - t < 100) {
if (esp.available()) { esp.read(); t = millis(); }
}
}
// Hidden temperature sensor inside the ATmega328P (ADC channel 8)
int readChipTemp() {
ADMUX = (1 << REFS1) | (1 << REFS0) | (1 << MUX3); // 1.1V ref, ch 8
ADCSRA |= (1 << ADEN); // turn the ADC on
delay(10); // let the reference settle
ADCSRA |= (1 << ADSC); // start a conversion
while (ADCSRA & (1 << ADSC)); // wait until it's done
return (ADCW - 324.31) / 1.22; // rough conversion to °C
}
void blinkLed(int times) {
for (int i = 0; i < times; i++) {
digitalWrite(LED, HIGH); delay(150);
digitalWrite(LED, LOW); delay(150);
}
digitalWrite(LED, ledOn); // back to the ON/OFF state
}
void setup() {
Serial.begin(9600);
esp.begin(9600);
pinMode(LED, OUTPUT);
randomSeed(analogRead(A0)); // unconnected pin = random noise
secret = random(1, 101); // 1..100
delay(2000);
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=\"Panel_" MY_NAME "\",\"12345678\",5,3", 2000);
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,80", 1000);
Serial.println("Join 'Panel_" MY_NAME "' then open http://192.168.4.1");
}
loop() is the same parsing pattern as Step 5a (slide 31). Only the indexOf() checks are new.
/favicon.ico too. We just hang up on itindexOf("n=") + 2 jumps to the number in /guess?n=42F("...") keeps the HTML in Flash (32 KB) instead of RAM (2 KB)playMorse() from Project A)<meta http-equiv='refresh' content='5;url=/'>// PROJECT B — PHONE CONTROL PANEL (Part 2 of 2)
void loop() {
if (esp.available() && esp.find("+IPD,")) {
int connId = esp.parseInt();
esp.find(":");
String req = esp.readStringUntil('\n'); // "GET /on HTTP/1.1"
skipRest();
Serial.println(req);
if (req.indexOf("favicon") != -1) { // browser wants an icon:
esp.println("AT+CIPCLOSE=" + String(connId)); // ignore it
return;
}
if (req.indexOf("/on") != -1) ledOn = true;
if (req.indexOf("/off") != -1) ledOn = false;
digitalWrite(LED, ledOn);
if (req.indexOf("/blink") != -1) blinkLed(6);
if (req.indexOf("/guess") != -1) checkGuess(req);
views++;
sendResponse(connId, buildPage());
}
}
void checkGuess(String req) {
// "GET /guess?n=42 HTTP/1.1" -> 42
int g = req.substring(req.indexOf("n=") + 2).toInt();
tries++;
if (g < secret) gameMsg = String(g) + " is too LOW ⬆";
else if (g > secret) gameMsg = String(g) + " is too HIGH ⬇";
else {
gameMsg = "🎉 " + String(g) + " is RIGHT! " + String(tries) +
" tries. New number chosen!";
blinkLed(10); // victory light show
secret = random(1, 101);
tries = 0;
}
}
String buildPage() {
String p;
p.reserve(1200); // grab RAM for the page in one go
// F("...") keeps the text in Flash (32 KB) instead of RAM (2 KB)
p = F("<!DOCTYPE html><html><head><meta charset='utf-8'>"
"<meta name='viewport' content='width=device-width'><style>"
"body{font-family:sans-serif;text-align:center;"
"background:#1a1a2e;color:#fff}"
".c{background:#2a2a50;border-radius:14px;padding:12px;"
"margin:12px auto;max-width:340px}"
"a.b{display:inline-block;padding:14px 20px;margin:4px;"
"border-radius:10px;color:#fff;text-decoration:none}"
"input,button{font-size:18px;padding:8px;border-radius:8px}"
"</style></head><body><h2>");
p += MY_NAME;
p += F("'s Arduino</h2><div class='c'><h3>💡 LED is ");
p += ledOn ? "ON" : "OFF";
p += F("</h3><a class='b' style='background:#28a745' href='/on'>ON</a>"
"<a class='b' style='background:#dc3545' href='/off'>OFF</a>"
"<a class='b' style='background:#6f42c1' href='/blink'>BLINK</a>"
"</div><div class='c'>⏱ Uptime: ");
p += millis() / 1000;
p += F(" s<br>🌡 Chip temp: ");
p += readChipTemp();
p += F(" °C<br>👀 Page views: ");
p += views;
p += F("</div><div class='c'><h3>🎯 Guess my number</h3><p>");
p += gameMsg;
p += F("</p><form action='/guess'><input name='n' type='number' "
"min='1' max='100'> <button>Guess</button></form></div>"
"<a href='/' style='color:#aaa'>🔄 Refresh</a></body></html>");
return p;
}
The problem with the Arduino IDE: as your project grows, stuffing all your HTML inside C++ strings becomes messy and hard to maintain. Let's fix that.
WiFi_LED_ControllerPlatformIO creates a proper folder structure. Here's how we'll organize the LED controller project:
src/ — Your main C++ code (replaces .ino)include/ — Header files (.h) for HTML, CSS, and configplatformio.ini — Board & library settings (auto-generated)String html = "<!DOCTYPE html><html>"
"<head><style>body{font-family:"
"sans-serif}..." // 🤮 messy!
// main.cpp
#include "html_page.h"
// Just use: buildHtmlPage(led1, led2)
main.cpp not .ino#include <Arduino.h> at the topsetup(), loop(), digitalWrite(), etc.This header stores all Wi-Fi and pin settings in one place. If you change your SSID, password, or pin numbers, you only update this one file.
#ifndef?#ifndef NAME → "if not already defined"#define NAME → "mark as defined"...your code...#endif → "end of guard"
include/ folder in VS Code → New File → wifi_config.h
// include/wifi_config.h
#ifndef WIFI_CONFIG_H
#define WIFI_CONFIG_H
// ==============================
// Wi-Fi Access Point Settings
// ==============================
#define AP_SSID "Arduino_WiFi"
#define AP_PASSWORD "12345678"
#define AP_CHANNEL 5
#define AP_ENCRYPT 3 // WPA2_PSK
// ==============================
// Pin Assignments
// ==============================
#define LED1_PIN 12
#define LED2_PIN 13
// ==============================
// ESP-01 Serial Settings
// ==============================
#define ESP_RX_PIN 2
#define ESP_TX_PIN 3
#define ESP_BAUD 9600
#endif // WIFI_CONFIG_H
The CSS styles go into their own header file. This keeps the styling completely separate from the HTML structure and the C++ logic.
R"rawliteral(...)rawliteral" let you write HTML/CSS exactly as-is — no escaping quotes or special characters needed!
include/html_style.h
// include/html_style.h
#ifndef HTML_STYLE_H
#define HTML_STYLE_H
const char CSS_STYLE[] PROGMEM = R"rawliteral(
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
background: #f0f0f0;
}
h1 {
color: #2d3436;
font-size: 24px;
}
h2 { color: #636e72; }
.btn {
display: inline-block;
padding: 15px 30px;
margin: 8px;
font-size: 18px;
border: none;
border-radius: 10px;
cursor: pointer;
color: #fff;
text-decoration: none;
}
.on { background: #28a745; }
.off { background: #dc3545; }
</style>
)rawliteral";
#endif // HTML_STYLE_H
This header contains a function that builds the HTML page. It takes the LED states as parameters and returns the complete HTML string.
html_style.hled1 and led2 boolean statesStringString page = buildHtmlPage(led1State, led2State);include/html_page.h
// include/html_page.h
#ifndef HTML_PAGE_H
#define HTML_PAGE_H
#include <Arduino.h>
#include "html_style.h"
String buildHtmlPage(bool led1, bool led2) {
String page = "<!DOCTYPE html><html><head>";
page += "<meta name='viewport' "
"content='width=device-width'>";
page += "<title>LED Control</title>";
// Add CSS from html_style.h
page += CSS_STYLE;
page += "</head><body>";
page += "<h1>Arduino LED Control</h1>";
// LED 1 section
page += "<h2>LED 1: ";
page += (led1 ? "ON" : "OFF");
page += "</h2>";
page += "<a href='/LED1=ON' class='btn on'>"
"LED1 ON</a>";
page += "<a href='/LED1=OFF' class='btn off'>"
"LED1 OFF</a><br>";
// LED 2 section
page += "<h2>LED 2: ";
page += (led2 ? "ON" : "OFF");
page += "</h2>";
page += "<a href='/LED2=ON' class='btn on'>"
"LED2 ON</a>";
page += "<a href='/LED2=OFF' class='btn off'>"
"LED2 OFF</a>";
page += "</body></html>";
return page;
}
#endif // HTML_PAGE_H
The main file is now clean and focused — it only handles the Arduino logic. All HTML and config are imported from headers.
| Before: | ~90 lines, all in one file |
| After: | ~65 lines in main.cpp |
| + clean HTML in html_page.h | |
| + clean CSS in html_style.h | |
| + config in wifi_config.h |
#include <Arduino.h> is requiredsetup()#include for config and HTML// src/main.cpp
#include <Arduino.h>
#include <SoftwareSerial.h>
#include "wifi_config.h"
#include "html_page.h"
SoftwareSerial esp(ESP_RX_PIN, ESP_TX_PIN);
bool led1State = false;
bool led2State = false;
// Forward declaration
String sendATCommand(String cmd, int timeout);
void setup() {
Serial.begin(9600);
esp.begin(ESP_BAUD);
pinMode(LED1_PIN, OUTPUT);
pinMode(LED2_PIN, OUTPUT);
delay(2000);
// Set up Access Point
sendATCommand("AT+CWMODE=2", 1000);
String sapCmd = "AT+CWSAP=\"" + String(AP_SSID)
+ "\",\"" + String(AP_PASSWORD) + "\","
+ String(AP_CHANNEL) + "," + String(AP_ENCRYPT);
sendATCommand(sapCmd, 3000);
sendATCommand("AT+CIPMUX=1", 1000);
sendATCommand("AT+CIPSERVER=1,80", 1000);
sendATCommand("AT+CIFSR", 1000);
Serial.println("--- LED Server Ready ---");
}
void loop() {
if (esp.available()) {
String req = esp.readString();
if (req.indexOf("+IPD") != -1) {
int idStart = req.indexOf("+IPD,") + 5;
int id = req.substring(idStart,
idStart + 1).toInt();
// Parse LED commands
if (req.indexOf("LED1=ON") != -1)
{ led1State = true;
digitalWrite(LED1_PIN, HIGH); }
if (req.indexOf("LED1=OFF") != -1)
{ led1State = false;
digitalWrite(LED1_PIN, LOW); }
if (req.indexOf("LED2=ON") != -1)
{ led2State = true;
digitalWrite(LED2_PIN, HIGH); }
if (req.indexOf("LED2=OFF") != -1)
{ led2State = false;
digitalWrite(LED2_PIN, LOW); }
// Build page from html_page.h
String html = buildHtmlPage(
led1State, led2State);
esp.println("AT+CIPSEND=" + String(id)
+ "," + String(html.length()));
delay(100);
esp.print(html);
delay(300);
esp.println("AT+CIPCLOSE=" + String(id));
}
}
}
String sendATCommand(String cmd, int t) {
String r = "";
esp.println(cmd);
long m = millis();
while (millis() - m < t)
while (esp.available())
r += (char)esp.read();
Serial.println(r);
return r;
}
Follow these steps to create the WiFi LED Controller project using PlatformIO:
WiFi_LED_Controller, board = Arduino Unoinclude/wifi_config.h — copy the config codeinclude/html_style.h — copy the CSS codeinclude/html_page.h — copy the page buildersrc/main.cpp — copy the main codeArduino_WiFihttp://192.168.4.1 in the browser#include <Arduino.h> in main.cppsrc/ instead of include/#ifndef / #endif).ino extension instead of .cpphtml_scripts.h for JavaScript (auto-refresh)WiFi_LED_Controller folder and submit it. Your instructor will check that the code is properly organized across the 4 files.
Test your understanding of AT commands and ESP-01 configuration:
AT+CWJAP — Join WiFiAT+CWSAP — Configure APAT+CIFSR — Get IPAT+CIPMUX — Multi-connAT+CIPSERVER — Start serverAT+CIPSEND — Send data
| Command | What it does |
|---|---|
AT | Test — responds OK |
AT+RST | Reset the ESP module |
AT+CWMODE=1 | Station mode (join WiFi) |
AT+CWMODE=2 | AP mode (create hotspot) |
AT+CWMODE=3 | Both Station + AP |
AT+CWJAP="ssid","pw" | Connect to a WiFi network |
AT+CWSAP="name","pw",ch,enc | Configure AP (name, password, channel, encryption) |
AT+CIFSR | Get IP address |
AT+CIPMUX=1 | Enable multiple connections |
AT+CIPSERVER=1,80 | Start TCP server on port 80 |
AT+CIPSEND=id,len | Send len bytes on connection id |
AT+CIPCLOSE=id | Close connection id |
| Pattern | Meaning |
|---|---|
+IPD,id,len:data | Received len bytes from connection id |
OK | Command succeeded |
ERROR | Command failed |
SEND OK | Data sent successfully |
> | Ready for data (after CIPSEND) |
| Function | What it does |
|---|---|
esp.available() | Returns number of bytes waiting to be read |
esp.read() | Reads one byte (as int). Use - '0' to convert ASCII digit |
esp.readString() | Reads all available data as a String (blocks until timeout) |
esp.find("text") | Reads until "text" found → true, or timeout → false. Consumes data! |
esp.println("cmd") | Sends command + newline to ESP |
esp.print(data) | Sends data without newline |
esp.write(byte) | Sends a single raw byte |
esp.setTimeout(ms) | Sets timeout for find/readString (default 1000ms) |
| Pattern | Use |
|---|---|
int id = esp.read() - '0'; | Get connection ID as integer (ASCII trick) |
if (esp.find("+IPD,")) | Wait for incoming client request |
String s = esp.readString(); | Read full request after +IPD detected |
s.indexOf("/led/on") | Check if request URL contains a path |
while(millis()-t < 3000) | Non-blocking timeout loop |