Generating PDF…

Preparing…
← Back

WiFi Communication with ESP8266 ESP-01

DE6417 — Microcontrollers 2 · Week 12

PCINT Review → ESP-01 Hardware → AT Commands → Mini Projects

Today's Agenda

🔄 Part 1: PCINT Review

Quick warm-up exercises on pin change interrupts from last week

📡 Part 2: ESP8266 ESP-01

Hardware overview, pinout, wiring to Arduino Uno

⌨️ Part 3: AT Commands

Communicating with the ESP-01 via serial AT commands

🚀 Part 4: Mini Projects

Choose your project: WiFi Walkie-Talkie or Phone Control Panel (no extra parts!)

Part 1: PCINT Review

Quick warm-up from Week 9

PCINT Quick Recap

GroupPortPinsVectorPCICR BitMask
0BD8–D13PCINT0_vectPCIE0PCMSK0
1CA0–A5PCINT1_vectPCIE1PCMSK1
2DD0–D7PCINT2_vectPCIE2PCMSK2
Remember: PCINT triggers on both edges (rising AND falling). You must check the pin state inside the ISR to determine the direction.
// 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();

Review Exercise: PCINT for Pin A2

You want a pin change interrupt on analog pin A2. Fill in each blank:

Port
PCINT
Group
PCICR |= (1 << );
|= (1 << );
ISR( ) { ... }
if ( & (1 << ))
Pin Mapping Cheat Sheet

Port C (Analog):
A0 = PC0 = PCINT8
A1 = PC1 = PCINT9
A2 = PC2 = PCINT10
A3 = PC3 = PCINT11
A4 = PC4 = PCINT12
A5 = PC5 = PCINT13
Formula:
PCINT# = 8 + analog pin number
e.g. A2 → PCINT(8+2) = PCINT10

Review Exercise 2: PCINT for Pin D10

Configure a pin change interrupt on digital pin D10. Fill in each blank:

Port
PCINT
Group
PCICR |= (1 << );
|= (1 << );
ISR( ) { ... }
if ( & (1 << ))
&= ~(1 << PB2);   |= (1 << PB2);
Pin Mapping Cheat Sheet

Port B (Digital 8–13):
D8 = PB0 = PCINT0
D9 = PB1 = PCINT1
D10 = PB2 = PCINT2
D11 = PB3 = PCINT3
D12 = PB4 = PCINT4
D13 = PB5 = PCINT5
Formula:
Port B: PCINT# = digital pin − 8
e.g. D10 → PCINT(10−8) = PCINT2

Group 0 covers all of Port B.

Review Exercise 3: PCINT for Pin D4

Configure a pin change interrupt on digital pin D4. Fill in each blank:

Port
PCINT
Group
PCICR |= (1 << );
|= (1 << );
ISR( ) { ... }
if ( & (1 << ))
if (!( & (1 << ))) { /* falling */ }
Pin Mapping Cheat Sheet

Port D (Digital 0–7):
D0 = PD0 = PCINT16
D1 = PD1 = PCINT17
D2 = PD2 = PCINT18
D3 = PD3 = PCINT19
D4 = PD4 = PCINT20
D5 = PD5 = PCINT21
D6 = PD6 = PCINT22
D7 = PD7 = PCINT23
Formula:
Port D: PCINT# = 16 + pin number
e.g. D4 → PCINT(16+4) = PCINT20

Group 2 covers all of Port D.
Falling edge detection:
Since PCINT fires on both edges, negate the pin read to check for LOW (falling edge).

Part 2: ESP8266 ESP-01

Adding WiFi to your Arduino

What is the ESP-01?

  • WiFi module based on the ESP8266 chip by Espressif
  • Supports 802.11 b/g/n (2.4 GHz)
  • Controlled via AT commands over serial (UART)
  • Operating voltage: 3.3V (NOT 5V tolerant!)
  • Can act as Station (connect to WiFi) or Access Point (create WiFi)
  • Only 8 pins — simple and compact
⚠️ Critical: The ESP-01 runs on 3.3V. Connecting it directly to Arduino's 5V pins will damage it. Use a voltage divider or level shifter on the TX→RX line.
📋 ESP-01 Specifications
ChipESP8266EX
WiFi802.11 b/g/n
Voltage3.3V
Current (peak)~170 mA
Flash1 MB
GPIO Pins2 (GPIO0, GPIO2)
UARTTX, RX
Baud Rate9600 or 115200 (varies)

ESP-01 Pinout

PinNameFunction
1VCC3.3V power supply
2GNDGround
3TXTransmit data (to Arduino RX)
4RXReceive data (from Arduino TX)
5RSTReset (active LOW)
6CH_PD / ENChip enable (pull HIGH)
7GPIO0General purpose I/O
8GPIO2General purpose I/O
ESP-01 Module — Top View
GND
ESP8266
ESP-01 802.11 b/g/n ⚡ 3.3V ONLY
VCC (3.3V)
GPIO2
RST
GPIO0
CH_PD / EN
RX
TX
Power Ground TX RX GPIO Enable Reset

Wiring ESP-01 to Arduino Uno

ESP-01 Pin→Arduino / PowerNotes
VCC→3.3VUse Arduino 3.3V output
GND→GNDCommon ground
TX→Pin 2 (SoftwareSerial RX)Direct connection OK
RX→Pin 3 via voltage divider5V → 3.3V needed!
CH_PD / EN→3.3VMust 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
⚠️ Voltage Divider for RX

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

Arduino Uno R3 3.3V 5V GND D2 (RX) D3 (TX) ESP-01 VCC GND CH_PD TX RX direct 1kΩ 2kΩ GND 5V out 3.3V Power TX/RX RX/TX (divider)
💡 Why SoftwareSerial?
We use pins 2 & 3 instead of hardware serial (pins 0 & 1) so that the USB serial monitor stays available for debugging. The SoftwareSerial library creates a second serial port.
📦 Do I need to install SoftwareSerial?
No! 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.

First Connection Test

Upload this sketch to verify your ESP-01 is responding:

  1. Wire up the ESP-01 as shown on the previous slide
  2. Upload the code (right)
  3. Open Serial Monitor at 9600 baud
  4. Set line ending to "Both NL & CR"
  5. Type AT and press Enter
  6. You should see OK
✅ Expected output:
AT → OK
If you see garbage text, your ESP may be at 115200 — see the next slide to detect & fix it.
Troubleshooting:
• No response → Check wiring & CH_PD is HIGH
• Garbled text → ESP is probably at 115200, use the baud rate detector (next slide)
• "busy" → ESP is still booting, wait 2 sec
#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());
  }
}

⚠️ Baud Rate Problem

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.

How do you know which one yours is?
Upload the baud rate detector sketch (right) — it tries both speeds and tells you which one works.

What to look for

Serial Monitor OutputMeaning
ESP responding at 9600Already at 9600 ✅ — you're good!
ESP responding at 115200Needs to be changed → next slide
No response at either rateCheck wiring & CH_PD
💡 Why 9600?
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() { }

Changing Baud Rate to 9600

If your ESP is at 115200, use this sketch to permanently change it to 9600:

✅ AT+UART_DEF=9600,8,1,0,0
This command changes the default baud rate. It is saved to flash — the ESP remembers it even after power off.

Command Breakdown

ParameterValueMeaning
Baud rate9600New speed
Data bits8Standard
Stop bits1Standard
Parity0None
Flow control0Disabled
⚠️ After running this sketch:
1. Upload the Baud Rate Detector again to confirm it now responds at 9600.
2. From now on, use 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() { }

Part 3: AT Commands

Talking to the ESP-01

Essential AT Commands

CommandDescriptionExample Response
ATTest connectionOK
AT+RSTReset moduleready
AT+GMRFirmware versionAT version: ...
AT+CWMODE=1Set Station modeOK
AT+CWMODE=2Set AP modeOK
AT+CWMODE=3Set Station + APOK
AT+CWJAP="ssid","pass"Connect to WiFiWIFI CONNECTED
AT+CIFSRGet IP address+CIFSR:STAIP,"..."
AT+CIPMUX=1Enable multiple connectionsOK
AT+CIPSERVER=1,80Start TCP server on port 80OK
WiFi Modes Explained:
  • Mode 1 (Station): ESP connects to an existing WiFi network — like your phone connecting to home WiFi
  • Mode 2 (AP): ESP creates its own WiFi hotspot — other devices connect to it
  • Mode 3 (Both): Does both simultaneously
📝 Important Notes:
  • Every command ends with \r\n (carriage return + newline)
  • Strings must use double quotes inside AT commands
  • Commands are case-sensitive

Interactive: AT Command Simulator

Try typing AT commands below. The simulator responds like a real ESP-01:

Connecting to WiFi (Station Mode)

AT+CWMODE=1
Set Station mode
↓
AT+CWJAP="SSID","PASS"
Connect to network
↓
Wait for WIFI CONNECTED
+ WIFI GOT IP
↓
AT+CIFSR
Get assigned IP
AT+CWMODE=1
OK
AT+CWJAP="LabWiFi","password123"
WIFI CONNECTED
WIFI GOT IP
OK
AT+CIFSR
+CIFSR:STAIP,"192.168.1.42"
+CIFSR:STAMAC,"aa:bb:cc:dd:ee:ff"
OK
✅ You're on the network!
The ESP now has IP 192.168.1.42. Other devices on the same network can communicate with it.

Finding the NZSE Wi-Fi SSID

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:

📱 Option 1 — Check Your Phone or Laptop
  1. Open Wi-Fi Settings on your phone or laptop
  2. Look at the network you are currently connected to
  3. The network name shown is your SSID
📡 Option 2 — Scan with the ESP-01
Send the command AT+CWLAP via Serial Monitor. The ESP will list all visible networks:
AT+CWLAP
+CWLAP:(3,"NZSE-Student",-45,...)
+CWLAP:(3,"NZSE-Staff",-52,...)
+CWLAP:(0,"Guest-WiFi",-70,...)
OK

The format is: (encryption, "SSID", signal_strength, ...)

⚠️ SSID Tips
  • The SSID is case-sensitive — "NZSE-Student" is different from "nzse-student"
  • Copy the name exactly as it appears in the scan results
  • If you see multiple NZSE networks, use the one you normally connect to on your laptop
🔑 Getting the Password
  • The Wi-Fi password is usually provided by your instructor at the start of the lab session
  • On Windows: Settings → Network → Wi-Fi → your network → Properties → "Show password"
  • On macOS: System Settings → Wi-Fi → click (i) next to the network → "Show password"
  • You can also check Keychain Access (macOS) or netsh wlan show profile name="SSID" key=clear (Windows CMD)

Helper: sendATCommand()

Writing AT command code gets repetitive. This helper function sends a command and waits for a response:

Usage:
sendATCommand("AT+CWMODE=2", 1000);
sendATCommand("AT+CWSAP=...", 3000);

The function sends the command, waits up to timeout ms, and prints the ESP's response to Serial Monitor.
💡 Why this matters:
Without this helper, you'd need to repeat the send-wait-read pattern for every single AT command. This keeps your code clean.
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);
}

Connecting to NZSE Wi-Fi

Replace YOUR_SSID and YOUR_PASSWORD with the actual values from the previous slide:

1. Set Station Mode
AT+CWMODE=1
↓
2. Connect
AT+CWJAP="SSID","PASS"
↓
3. Wait ~5-10 seconds
for WIFI CONNECTED
↓
4. Check IP
AT+CIFSR
⚠️ Common Errors:
  • FAIL → Wrong SSID or password
  • DISCONNECT → Out of range or network full
  • No response → ESP may need a reset (AT+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());
}

Verifying: Send a GET Request

Once connected to NZSE Wi-Fi, verify the connection actually works by fetching a real web page. We'll request example.com:

Already connected
WIFI GOT IP
↓
AT+CIPSTART="TCP","example.com",80
Open TCP connection
↓
AT+CIPSEND=length
Tell ESP how many bytes to send
↓
Send HTTP request text
GET / HTTP/1.1\r\nHost: example.com\r\n\r\n
↓
Read response
HTML from example.com
// Open TCP to example.com on port 80
AT+CIPSTART="TCP","example.com",80
CONNECT
OK
// Tell ESP we'll send 43 bytes
AT+CIPSEND=43
OK
> ← ready for data
// Send the HTTP GET request
GET / HTTP/1.1\r\nHost: example.com\r\n\r\n
SEND OK
// Response arrives from the server
+IPD,1256:HTTP/1.1 200 OK
...
<h1>Example Domain</h1>
...
✅ If you see HTTP/1.1 200 OK — you are connected to the internet through NZSE Wi-Fi!

GET Request — Full Code

This sketch connects to NZSE Wi-Fi and then fetches a page from example.com to prove internet connectivity:

📝 How the byte count works:
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).
✅ Expected Serial Monitor Output:
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());
}

Build a Web Server in 6 Steps

Today your Arduino becomes a tiny website. A phone will ask it for a page, and it will answer.

📱
Phone
asks for a page
⇄
WiFi
📡
ESP-01
the radio
⇄
AT cmds
🧠
Arduino
the brain
1
Make the hotspot so the phone can join 🖐💻
2
Open the door start a server on port 80 🖐💻
3
Read the request what did the phone send? 🖐
4
Answer it type a reply yourself 🖐
5
Automate 3 + 4 let the code do it 💻
6
Do what was asked /led/on lights the LED 💻

🖐 By hand = type AT commands yourself   💻 In code = the Arduino types them

How every step works

1
🖐 By hand Type it yourself in the Serial Monitor, and see exactly what the ESP replies.
2
💻 In code Upload a sketch that types it for you. Each sketch is the previous one plus a few highlighted lines.
3
👀 Check the Try-it box. Your screen or phone should match it before you move on.

Which sketch is on my Arduino?

Every slide tells you in a bar at the top:

▶ On your Arduino: Passthrough sketch: you type, it forwards to the ESP
▶ On your Arduino: Upload the Step N sketch shown on the slide
▶ On your Arduino: Keep the last sketch. No upload.

Uploading resets only the Arduino, not the ESP, so anything you set up by hand keeps running.

1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Passthrough sketch (slide 12). Serial Monitor: 9600, "Both NL & CR". Then type the commands below.
Show the passthrough sketch
#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
}

🖐 By hand Step 1: Make the Hotspot

Station mode (slides 18–23)
📱 → 📡 ← ESP
ESP joins a network
AP mode (today)
📱 → ESP
ESP is the network
1
AT+CWMODE=2 become a hotspot
2
AT+CWSAP="ESP_Reza","12345678",5,3
name, password (8+ chars!), channel 5, WPA2 security
3
AT+CIFSR its address is always 192.168.4.1
// You type (blue) · ESP answers (green)
AT+CWMODE=2
OK
AT+CWSAP="ESP_Reza","12345678",5,3
OK
AT+CIFSR
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"aa:bb:cc:dd:ee:ff"
OK
👀 Try it: open WiFi settings on your phone. ESP_Reza (your name!) is in the list. Join it with the password.
💡 Two tips: use your own name in the hotspot name (20 hotspots called MyESP is chaos), and turn off mobile data so your phone doesn't escape back to 4G.
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Upload the Step 1 sketch shown on the right.

💻 In code Step 1

Now let the Arduino type those 3 commands for you, every time it starts.

What's in this sketch:
  • sendATCommand(): our helper from slide 20
  • Highlighted: the 3 commands you just typed
  • loop(): the slide 12 passthrough, so you can still watch everything and type extra commands
👀 Try it: upload, open Serial Monitor. You see three OKs 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());
}
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Keep the Step 1 sketch running. No upload. Its loop() is the passthrough, so you can type commands.

🖐 By hand Step 2: Open the Door

The phone can join the hotspot, but nobody is listening yet. Two commands start a web server:

1
AT+CIPMUX=1 allow several visitors at once
2
AT+CIPSERVER=1,80 1 = start server, 80 = the web port
🚪 Why port 80? A port is like a door number. Browsers always knock on door 80 unless told otherwise.
🔢 Why CIPMUX=1? Each visitor gets a connection ID: the first is 0, then 1, 2... We'll need that number to reply to the right visitor. (A server needs CIPMUX=1, or CIPSERVER gives ERROR.)
AT+CIPMUX=1
OK
AT+CIPSERVER=1,80
OK
📞 Think of it as a phone call. Step 1 bought the phone. Step 2 switches it on. Next, someone calls...
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Upload the Step 2 sketch shown on the right.

💻 In code Step 2

Add the two commands to setup(). loop() is still the passthrough, so you see everything the ESP says.

👀 Try it: upload, then on the phone open http://192.168.4.1. Watch the Serial Monitor:
0,CONNECT
+IPD,0,398:GET / HTTP/1.1
Host: 192.168.4.1
User-Agent: Mozilla/5.0 (iPhone...
Accept: text/html,...
...
🌀 The phone keeps spinning. That's correct! It asked for a page and nobody answered yet. Leave this sketch on the Arduino for Steps 3 and 4.
#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());
}
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Keep the Step 2 sketch running. No upload. Just read what it printed.

🖐 By eye Step 3: Read the Request

Look at the line that just appeared. Every incoming message starts with +IPD and has 4 parts:

+IPD,0,398:GET / HTTP/1.1 ...
+IPD"data arrived!"
0who sent it
(connection ID)
398how many bytes
GET / ...the request

Only the first line matters to us. The part between GET and HTTP is the path, i.e. what they want:

Phone opensFirst line of the request
192.168.4.1GET / HTTP/1.1
192.168.4.1/led/onGET /led/on HTTP/1.1

✋ Quick check

+IPD,2,6:LED=ON
👀 Try it: on the phone, open 192.168.4.1/hello. Find /hello in the Serial Monitor. Does the connection ID change?
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Keep the Step 2 sketch running. No upload. Type into the Serial Monitor while the phone is still spinning.

🖐 By hand Step 4: Answer It Yourself

While the phone is still spinning, you reply. It's a 3-move handshake:

1
Announce: "client 0, I'm sending 7 bytes"
YouAT+CIPSEND=0,7
ESP> "OK, go ahead"
2
Send exactly 7 bytes
YouHello + Enter
ESPSEND OK
3
Hang up
YouAT+CIPCLOSE=0
ESP0,CLOSED
👀 Try it: the phone stops spinning and shows Hello. You just served a web page by typing! 🎉
🤔 Why 7 and not 5? When you press Enter, Serial Monitor adds 2 invisible bytes: \r\n (that's what "Both NL & CR" means).
H e l l o \r \n  → 5 + 2 = 7
DataBytesCommand
Hi + Enter4AT+CIPSEND=0,4
Hello + Enter7AT+CIPSEND=0,7
<h1>Hi</h1> + Enter13AT+CIPSEND=0,13
⚠️ The count must be exact. Too many bytes → ERROR. Too few → the ESP waits for the rest.
Phone shows an error instead? Some browsers insist on a short HTTP "envelope" before the page. We add one in Step 5. You may also see a 2nd visitor asking for /favicon.ico: ignore it.
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Upload the Step 5a sketch shown on the right. From now on the code does the typing, so typed commands no longer reach the ESP.

💻 In code Step 5a: Read the Request

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.

1
esp.find("+IPD,") → true
+IPD,0,398:GET / HTTP/1.1
2
esp.parseInt() → 0
+IPD,0,398:GET / HTTP/1.1
3
esp.find(":") → true
+IPD,0,398:GET / HTTP/1.1
4
readStringUntil('\n') → "GET / HTTP/1.1"
+IPD,0,398:GET / HTTP/1.1⏎ Host: ...
5
skipRest() → buffer empty, ready for the next visitor
👀 Try it: refresh the phone. Serial Monitor prints Client 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);
  }
}
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Upload the Step 5b sketch shown on the right.

💻 In code Step 5b: Answer Automatically

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
✉️ The header tells the browser: "200 OK, this is HTML, I'll close when done". It makes every browser happy.
print, not println: println would add 2 bytes we didn't count!
👀 Try it: refresh the phone. Hello from ESP! appears instantly, every time. 🎉
#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!");
  }
}
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide
▶ On your Arduino: Upload the Step 6 sketch shown on the right.

💻 In code Step 6: Do What Was Asked

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:
"GET /led/on HTTP/1.1"
 01234 ← found at 4
So != -1 just means "found it".
👀 Try it on the phone:
  • 192.168.4.1/led/on → "LED is ON" and the L LED lights 💡
  • 192.168.4.1/led/off → LED off
  • 192.168.4.1/anything → "Hello from ESP!"
That's a complete web server! 🏁 Typing URLs is clunky, though. Project B adds buttons to the page.
#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);
  }
}
1 Hotspot2 Door3 Request4 Answer5 Automate6 Decide

Recap: The Whole Conversation

Step 1–2 · in setup(), once
1Arduino → ESPAT+CWMODE=2 · AT+CWSAP=...make the hotspot
2Arduino → ESPAT+CIPMUX=1 · AT+CIPSERVER=1,80open the door
Step 3–6 · in loop(), every visit
3ESP → Arduino+IPD,0,398:GET /led/on HTTP/1.1the request
6ArduinoindexOf("/led/on") → LED ondecide
4Arduino → ESPAT+CIPSEND=0,len"len bytes coming"
4ESP → Arduino>"go ahead"
4Arduino → ESPHTTP/1.1 200 OK ... LED is ONthe page
4Arduino → ESPAT+CIPCLOSE=0hang up

What the phone shows

🔒 192.168.4.1/led/on
LED is ON
🔄 Every web visit is the same pattern:
+IPD → decide → CIPSEND → data → CIPCLOSE
🧩 Remember: anything you can type by hand, the Arduino can type for you. That's all sendATCommand() and sendResponse() are.

Part 4: Mini Projects

No extra parts: just your Arduino, your ESP-01 and your phone

Choose Your Project

🧰 Hardware: only the Arduino Uno + ESP-01 you already wired. Everything else is built in: the "L" LED on pin 13, a hidden temperature sensor inside the chip, Serial Monitor, and your phone.

📻 Project A: WiFi Walkie-Talkie

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.

AP + StationTCPPair

📱 Project B: Phone Control Panel

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!

AP modeWeb serverSolo
📻 A: Walkie-Talkie📱 B: Control Panel
Who talksArduino ⟷ ArduinoPhone → Arduino
WiFiBoard A = hotspot
Board B joins it
Arduino = hotspot
Phone joins it
You'll use+IPD, CIPSEND, text commands+IPD, sendResponse(), HTML forms
Coolest bitMorse code on your friend's LEDTemperature with no sensor wired
TeamPairs (2 boards)Solo
Difficulty⭐⭐⭐⭐⭐⭐
🏁 Finished early? Each project ends with Level-Up challenges. Still no extra parts needed.

📻 Project A: How It Works

📡
Board A (host)
IS_HOST true
Makes hotspot "Chat_Reza"
Server at 192.168.4.1:333
⟷
📻
Board B (guest)
IS_HOST false
Joins "Chat_Reza"
Connects to 192.168.4.1

✅ 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.

🧪 Test steps

  1. Agree on a ROOM name and PASSword together
  2. Upload with IS_HOST true to Board A, wait 10 s
  3. Upload with IS_HOST false to Board B, look for CONNECT
  4. Open both Serial Monitors: 9600 baud, line ending "Newline"
  5. Type away! 💬

Secret commands

You typeWhat happens on your friend's board
hello!Shows Reza: hello! + quick LED flash 🔔
/blink 5LED blinks 5 times 💡
/morse SOSLED flashes ... --- ... 📡
/pingReplies /pong automatically. You see the round-trip time in ms ⏱
// Board B's Serial Monitor
--- Walkie-Talkie ready! ---
Reza: hi from table 3 👋
You: hey! watch your LED...
[sent /morse HI]
[sent /ping]
Pong! Round trip: 142 ms
💡 Can you decode it? Close your eyes and let your partner send you a secret /morse word. First to read it wins!

📻 Project A: Code (1/2)

Settings, helpers and setup().

📝 Change these:
  • IS_HOST: true on one board, false on the other
  • MY_NAME: your nickname
  • ROOM + PASS: the same on both boards
New ideas in this code:
  • sendMsg() = CIPSEND to link 0, wait for >, then print
  • Each message ends with "\n" so the other side knows where it stops
  • The guest uses AT+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");
}

📻 Project A: Code (2/2)

loop() does two jobs: send what you type, and handle what arrives.

Spot the tricks:
  • msg.substring(7).toInt(): "/blink 5" → skip 7 chars → 5
  • MORSE[c - 'A']: 'C' - 'A' = 2 → the 3rd code. Letters are just numbers!
  • /ping stores millis(), and /pong subtracts it
🚀 Level-Up challenges
  1. /roll: both boards roll a dice with random(1,7). Highest wins
  2. /rps rock: rock-paper-scissors duel
  3. Add digits 0–9 to the Morse table
  4. /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();
}

📱 Project B: How It Works

📡
Arduino + ESP-01
Hotspot "Panel_Reza"
Web server at 192.168.4.1
📶
📱
Your phone
Joins "Panel_Reza"
Opens the page

Every tap = a new URL

You tapBrowser asks forArduino does
ON / OFFGET /on · GET /offSets the LED
BLINKGET /blinkBlinks 6 times
Guess "42"GET /guess?n=42Too high / too low / 🎉
🔄 RefreshGET /Fresh temperature + uptime

After every request, the Arduino builds the whole page again with the latest values and sends it with sendResponse().

Reza's Arduino
💡 LED is ON
ONOFFBLINK
⏱ Uptime: 312 s
🌡 Chip temp: 29 °C
👀 Page views: 14
🎯 Guess my number
42 is too HIGH ⬇
Guess
🌡 The hidden sensor
The ATmega328P has a thermometer inside the chip, on ADC channel 8. We read it with registers, just like PCINT!
🔥 Try it: press a warm finger on the big black chip for 20 s, then tap Refresh. (It's rough, ±10 °C, but you'll see it rise.)
🏆 Class challenge: swap phones with a neighbour. Who finds the number in the fewest guesses?

📱 Project B: Code (1/2)

Settings, helpers and setup().

📝 Change this: MY_NAME → your hotspot becomes Panel_YourName
What's new:
  • sendResponse() and skipRest() are the same helpers from slides 31 & 32
  • readChipTemp() sets ADMUX/ADCSRA bits by hand, like the PCINT registers
  • randomSeed(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");
}

📱 Project B: Code (2/2)

loop() is the same parsing pattern as Step 5a (slide 31). Only the indexOf() checks are new.

Spot the tricks:
  • favicon: browsers secretly ask for /favicon.ico too. We just hang up on it
  • indexOf("n=") + 2 jumps to the number in /guess?n=42
  • F("...") keeps the HTML in Flash (32 KB) instead of RAM (2 KB)
🚀 Level-Up challenges
  1. Add a 🌡 °F button
  2. Show a best score (fewest tries)
  3. Add a text box that flashes a word in Morse (borrow playMorse() from Project A)
  4. Auto-refresh: <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;
}

Better Workflow: PlatformIO + VS Code

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.

⚠️ The Problem with Arduino IDE
  • All code lives in one .ino file
  • HTML is buried inside C++ string concatenation
  • No syntax highlighting for the HTML
  • Difficult to debug or change the page layout
  • No folder structure — everything is flat
✅ The PlatformIO Solution
  • Write HTML in separate .h files with proper syntax
  • Organize code into multiple files
  • Use VS Code with autocomplete, IntelliSense, and linting
  • Professional project structure

Installing PlatformIO

  1. Open VS Code
  2. Go to Extensions (Ctrl+Shift+X / Cmd+Shift+X)
  3. Search for "PlatformIO IDE"
  4. Click Install — wait for it to finish
  5. Restart VS Code when prompted

Creating a New Project

  1. Click the PlatformIO Home icon (alien head 🐝) in the sidebar
  2. Click "New Project"
  3. Name: WiFi_LED_Controller
  4. Board: Arduino Uno
  5. Framework: Arduino
  6. Click Finish
💡 First time? PlatformIO will download the Arduino toolchain automatically. This may take a few minutes on slow connections.

Project Structure

PlatformIO creates a proper folder structure. Here's how we'll organize the LED controller project:

WiFi_LED_Controller/
├── platformio.ini
├── src/
│   └── main.cpp  ← Arduino code
└── include/
    ├── html_page.h  ← HTML template
    ├── html_style.h  ← CSS styles
    └── wifi_config.h ← Wi-Fi settings
📁 Folder purposes:
  • src/ — Your main C++ code (replaces .ino)
  • include/ — Header files (.h) for HTML, CSS, and config
  • platformio.ini — Board & library settings (auto-generated)

Why Separate Files?

Before (Arduino IDE) — one file:
String html = "<!DOCTYPE html><html>"
  "<head><style>body{font-family:"
  "sans-serif}..."  // 🤮 messy!
After (PlatformIO) — clean separation:
// main.cpp
#include "html_page.h"
// Just use: buildHtmlPage(led1, led2)
📝 Key Difference: .ino → .cpp
  • PlatformIO uses main.cpp not .ino
  • You must add #include <Arduino.h> at the top
  • Functions must be declared before use (or use header files)
  • Everything else works the same — setup(), loop(), digitalWrite(), etc.

File 1: wifi_config.h

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.

💡 What is #ifndef?
This is called an include guard. It prevents the file from being included twice, which would cause "redefinition" errors.

Pattern:
#ifndef NAME → "if not already defined"
#define NAME → "mark as defined"
...your code...
#endif → "end of guard"
📝 Create this file:
Right-click the 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

File 2: html_style.h

The CSS styles go into their own header file. This keeps the styling completely separate from the HTML structure and the C++ logic.

✅ Benefits:
  • Change the look without touching any C++ code
  • Easy to experiment with colors, sizes, layouts
  • Less clutter in your main code
⚠️ Why raw strings?
C++ raw strings R"rawliteral(...)rawliteral" let you write HTML/CSS exactly as-is — no escaping quotes or special characters needed!
📝 Create this file:
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

File 3: html_page.h

This header contains a function that builds the HTML page. It takes the LED states as parameters and returns the complete HTML string.

💡 How it works:
  1. Includes the CSS from html_style.h
  2. Takes led1 and led2 boolean states
  3. Builds HTML with correct ON/OFF labels
  4. Returns complete page as a String
Usage in main.cpp:
String page = buildHtmlPage(led1State, led2State);
That's it! One clean line instead of 20+ lines of string concatenation.
📝 Create: 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

File 4: main.cpp

The main file is now clean and focused — it only handles the Arduino logic. All HTML and config are imported from headers.

✅ Compare:
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
💡 Key differences from .ino:
  • #include <Arduino.h> is required
  • Helper functions declared before setup()
  • Uses #include for config and HTML
📤 Upload: Click the → arrow button in the PlatformIO toolbar (bottom of VS Code), or press Ctrl+Alt+U.
// 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;
}

Your Task: Build It!

Follow these steps to create the WiFi LED Controller project using PlatformIO:

Step-by-Step Instructions:
  1. Install PlatformIO extension in VS Code
  2. Create a new project: WiFi_LED_Controller, board = Arduino Uno
  3. Create include/wifi_config.h — copy the config code
  4. Create include/html_style.h — copy the CSS code
  5. Create include/html_page.h — copy the page builder
  6. Edit src/main.cpp — copy the main code
  7. Wire up your ESP-01 + 2 LEDs
  8. Click Upload (→ arrow in PlatformIO toolbar)
  9. Connect your phone to Arduino_WiFi
  10. Open http://192.168.4.1 in the browser
⚠️ Common PlatformIO Mistakes:
  • Forgetting #include <Arduino.h> in main.cpp
  • Putting .h files in src/ instead of include/
  • Missing include guards (#ifndef / #endif)
  • Using .ino extension instead of .cpp
🏆 Challenge Extensions:
  • Add a third LED — update all 4 files
  • Add an analog sensor reading to the page
  • Create a html_scripts.h for JavaScript (auto-refresh)
  • Change the CSS to use a dark theme
📤 Submitting:
Zip your entire WiFi_LED_Controller folder and submit it. Your instructor will check that the code is properly organized across the 4 files.

Exercise: AT Command Knowledge

Test your understanding of AT commands and ESP-01 configuration:

AT+CWMODE=
AT+CIPMUX=
Arduino TX is but ESP needs
Quick Reference

Modes:
1 = Station, 2 = AP, 3 = Both

Key Commands:
AT+CWJAP — Join WiFi
AT+CWSAP — Configure AP
AT+CIFSR — Get IP
AT+CIPMUX — Multi-conn
AT+CIPSERVER — Start server
AT+CIPSEND — Send data

Summary: Key Takeaways

✓ ESP-01 Basics
  • 3.3V module — use voltage divider!
  • Controlled via AT commands over UART
  • SoftwareSerial keeps USB debug free
  • CH_PD must be pulled HIGH
📡 WiFi Modes
  • Station: join existing network
  • AP: create your own hotspot
  • Both work for different use cases
⌨️ AT Command Flow
  1. Set mode (CWMODE)
  2. Connect/configure (CWJAP/CWSAP)
  3. Get IP (CIFSR)
  4. Enable multi-conn (CIPMUX)
  5. Start server (CIPSERVER)
🚀 Projects
  • Chat: TCP client/server, station mode
  • LED Control: Web server, AP mode
  • Both use the sendATCommand() helper

📋 ESP-01 Quick Reference

⚡ AT Commands

CommandWhat it does
ATTest — responds OK
AT+RSTReset the ESP module
AT+CWMODE=1Station mode (join WiFi)
AT+CWMODE=2AP mode (create hotspot)
AT+CWMODE=3Both Station + AP
AT+CWJAP="ssid","pw"Connect to a WiFi network
AT+CWSAP="name","pw",ch,encConfigure AP (name, password, channel, encryption)
AT+CIFSRGet IP address
AT+CIPMUX=1Enable multiple connections
AT+CIPSERVER=1,80Start TCP server on port 80
AT+CIPSEND=id,lenSend len bytes on connection id
AT+CIPCLOSE=idClose connection id

📨 Incoming Data Format

PatternMeaning
+IPD,id,len:dataReceived len bytes from connection id
OKCommand succeeded
ERRORCommand failed
SEND OKData sent successfully
>Ready for data (after CIPSEND)

🔧 ESP Serial Functions (Arduino)

FunctionWhat 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)

💡 Common Patterns

PatternUse
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