Arduino - Network Communication
Arduino - Modern Network Communication with ESP8266/ESP32
Section titled “Arduino - Modern Network Communication with ESP8266/ESP32”This tutorial has been completely updated to use modern, powerful, and cost-effective hardware. The original CC3000 WiFi module is obsolete. Today, the ESP8266 and ESP32 microcontrollers are the standard for adding WiFi to IoT projects. They are powerful, have built-in WiFi, and can be programmed directly from the Arduino IDE, often eliminating the need for a separate Arduino board.
We will build a WiFi-controlled switch. An ESP8266 will host a web server that you can access from any device on your network (phone, computer) to turn an LED on and off. This project is the foundation for countless home automation and IoT applications.
Required Components
Section titled “Required Components”- 1 × ESP8266 Development Board (e.g., NodeMCU or WEMOS D1 Mini)
- 1 × LED
- 1 × 220 Ohm Resistor
- 1 × Breadboard and jumper wires
Prerequisite: You must set up your Arduino IDE to program the ESP8266. Please follow a standard guide to add the ESP8266 board URL to your IDE’s Board Manager.
Circuit and Connections
Section titled “Circuit and Connections”The circuit is very simple. We’ll connect an LED to a GPIO pin of the ESP8266. On a WEMOS D1 Mini, pin D1 is a good choice.
WEMOS D1 Mini Pin Component--------------------------------------------- GND ---------------- (-) LED (short leg)
D1 ----------------- (220 Ohm Resistor) --- (+) LED (long leg)Many ESP8266 boards, like the NodeMCU and WEMOS D1 Mini, also have a built-in LED (usually on pin D4 or GPIO2). You can start with that and skip the external LED to test the code.
Modern Arduino Sketch for ESP8266
Section titled “Modern Arduino Sketch for ESP8266”This code creates a WiFi access point and a web server with simple endpoints to control the LED. This makes the project self-contained and easy to demonstrate.
/* * ESP8266 Web-Controlled LED * * This sketch creates a web server on the ESP8266 to control an LED. * It serves a simple HTML interface with buttons. */
#include <ESP8266WiFi.h>#include <ESP8266WebServer.h>
// --- Configuration ---// Replace with your network credentialsconst char* ssid = "YOUR_WIFI_SSID";const char* password = "YOUR_WIFI_PASSWORD";
const int ledPin = D1; // Pin for the LED (or use LED_BUILTIN)
// Create a web server object on port 80ESP8266WebServer server(80);
// --- Web Page HTML ---// Stored in Flash memory to save RAMconst char HTML_CONTENT[] PROGMEM = R"rawliteral(<!DOCTYPE html><html><head><title>ESP8266 LED Control</title><meta name="viewport" content="width=device-width, initial-scale=1"><style> body { font-family: Arial, sans-serif; text-align: center; margin: 50px; } .btn { display: inline-block; padding: 20px 40px; font-size: 24px; margin: 10px; cursor: pointer; } .on { background-color: #4CAF50; color: white; } .off { background-color: #f44336; color: white; }</style></head><body> <h1>LED Control</h1> <button class="btn on" onclick="location.href='/on'">ON</button> <button class="btn off" onclick="location.href='/off'">OFF</button></body></html>)rawliteral";
void handleRoot() { server.send(200, "text/html", HTML_CONTENT);}
void handleOn() { digitalWrite(ledPin, LOW); // LED is often active-low server.sendHeader("Location", "/"); server.send(302, "text/plain", "Redirecting...");}
void handleOff() { digitalWrite(ledPin, HIGH); // Set HIGH to turn off server.sendHeader("Location", "/"); server.send(302, "text/plain", "Redirecting...");}
void setup() { Serial.begin(115200); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); // Start with LED off
Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
Serial.println("\nWiFi connected!"); Serial.print("IP Address: "); Serial.println(WiFi.localIP());
// Define server routes server.on("/", handleRoot); server.on("/on", handleOn); server.on("/off", handleOff);
server.begin(); Serial.println("HTTP server started.");}
void loop() { // Handle incoming client requests server.handleClient();}Code Explanation
Section titled “Code Explanation”ESP8266WebServer: The core library for creating a web server on the ESP8266.R"rawliteral(...)rawliteral": This is a C++ raw string literal. It’s a modern way to define multi-line strings (like our HTML) without needing to escape characters like quotes or backslashes.- Server Routes:
server.on("/path", function)maps a URL path to a C++ function. When a client requestshttp://<IP>/,handleRootis called. Forhttp://<IP>/on,handleOnis called. - Redirection: After turning the LED on or off, we send a
302 Foundredirect response to send the user’s browser back to the main page. This provides a seamless user experience.
Running the Project
Section titled “Running the Project”- Replace
"YOUR_WIFI_SSID"and"YOUR_WIFI_PASSWORD"with your WiFi credentials. - Select your ESP8266 board (e.g., “WEMOS D1 R1 & mini”) and the correct COM port in the
Toolsmenu. - Upload the sketch.
- Open the Serial Monitor (set baud rate to 115200). It will print the IP address once connected to your WiFi.
- Open a web browser on a device connected to the same WiFi network and enter the IP address. You should see the control page.
- Click the ON and OFF buttons to control the LED!
Next Steps and Best Practices
Section titled “Next Steps and Best Practices”Electrical Safety: This tutorial uses a low-voltage LED. If you replace the LED with a relay to control mains-powered devices (like a lamp), you are working with lethal voltages. This requires deep knowledge of electrical safety, proper wiring, and insulation. Do not attempt to control mains voltage unless you are qualified to do so.
Going Further: For more robust IoT applications, consider using MQTT instead of a web server. MQTT is a lightweight messaging protocol designed for communication between devices and is the industry standard for IoT. You can also explore using mDNS (ESP8266mDNS library) to access your device with a friendly name like http://led-control.local instead of an IP address.