STA 模式:此时ESP8266模块是终端,可连接室内路由、手机热点或者AP热点
模块连接AP热点,可与其进行双向数据通信
模块连接手机热点,可与手机上的网络调试助手通信
模块连接路由器,可以在当前网络下的PC或者手机的网络调试助手通信
也可以通过路由接入互联网,从而手机或电脑通过互联网实现对设备的远程控制
AP 模式: ESP8266的默认模式,此时模块作为热点,实现手机的直接连接、STA模块的直接连接或电脑直接与模块通信,实现局域网无线通信。
STA+AP 模式:两种模式的共存模式,( STA 模式) 即可以通过路由器连接到互联网,并通过互联网控制设备;( AP 模式)即作为 wifi 热点,其他 wifi 设备连接到模块。这样实现局域网和广域网的无缝切换,方便操作。
STA模式下进行TCP Client通信

1 #include <ESP8266WiFi.h> 2 3 char* ssid = "your_wifi"; 4 char* passwd = "your_passwd"; 5 const uint16_t port = 8089; 6 const char * host = "192.168.1.7"; // your_Serverip 7 WiFiClient client; 8 9 void setup() { 10 Serial.begin(115200); 11 WiFi.mode(WIFI_STA); 12 WiFi.begin(ssid, passwd); 13 14 Serial.println("connecting to router... "); 15 //等待wifi连接成功 16 while (WiFi.status() != WL_CONNECTED) { 17 Serial.print("."); 18 delay(500); 19 } 20 Serial.println(""); 21 Serial.print("WiFi connected, local IP address:"); 22 Serial.println(WiFi.localIP()); 23 24 delay(500); 25 Serial.print("connecting to "); 26 Serial.println(host); 27 if (!client.connect(host, port)) { 28 Serial.println("connection failed"); 29 Serial.println("wait 5 sec..."); 30 delay(5000); 31 return; 32 }else 33 { 34 Serial.println("connect to tcp server success."); 35 Serial.println("Send this data to tcp server"); 36 client.println(String("hello tcp server")); 37 } 38 } 39 40 void loop() { 41 //读取从tcp server返回到响应数据 42 String recv_data = client.readStringUntil(' '); 43 Serial.println(recv_data); 44 45 if (0 == recv_data.compareTo("exit")) 46 { 47 Serial.println("closing connection"); 48 client.stop(); 49 } 50 delay(200); 51 }
STA模式下进行TCP Server通信
注意:设置CLIENTS_MAX_NUMS 大小,ESP8266最多支持5路Client同时连接。

1 #include <ESP8266WiFi.h> 2 #include <WiFiClient.h> 3 #include <WiFiServer.h> 4 #define CLIENTS_MAX_NUMS 4 5 /* Set these to your desired credentials. */ 6 const char *ssid = "your_wifi"; 7 const char *password = "your_passwd"; 8 WiFiServer server(8089); 9 WiFiClient serverClients[CLIENTS_MAX_NUMS]; 10 void setup() { 11 Serial.begin(115200); 12 WiFi.begin(ssid, password); 13 Serial.println(" connecting to router... "); 14 //等待wifi连接成功 15 while (WiFi.status() != WL_CONNECTED) { 16 Serial.print("."); 17 delay(500); 18 } 19 Serial.println(""); 20 Serial.print("WiFi connected, local IP address:"); 21 Serial.println(WiFi.localIP()); 22 23 delay(500); 24 Serial.println("Start tcp server..."); 25 server.begin(); 26 server.setNoDelay(true); 27 } 28 void loop() { 29 int i = 0; 30 if (server.hasClient()) 31 { 32 for (i = 0; i < CLIENTS_MAX_NUMS; i++) 33 { 34 if (!serverClients[i] || !serverClients[i].connected()) 35 { 36 if (serverClients[i]) 37 { 38 serverClients[i].stop(); 39 } 40 serverClients[i] = server.available(); 41 continue; 42 } 43 } 44 } 45 for (i = 0; i < CLIENTS_MAX_NUMS; i++) 46 { 47 if (serverClients[i] && serverClients[i].connected()) 48 { 49 if (serverClients[i].available()) 50 { 51 while (serverClients[i].available()) 52 { 53 String recv_data = serverClients[i].readStringUntil(' '); 54 Serial.println("recv data from tcp server:"); 55 Serial.println(recv_data); 56 // send back 57 serverClients[i].println(recv_data); 58 } 59 } 60 } 61 } 62 delay(50); 63 }
STA模式下进行HTTPClient通信
HTTPClient 获取深圳天气

1 #include <Arduino.h> 2 #include <ESP8266WiFi.h> 3 #include <ESP8266HTTPClient.h> 4 5 char* ssid = "your_wifi"; 6 char* passwd = "your_passwd"; 7 8 const uint16_t port = 80; 9 const char * host = "https://api.seniverse.com/v3/weather/now.json?key=SwwwfskBjB6fHVRon&location=shenzhen&language=zh-Hans&unit=c";//注:key为作者所有,仅供测试用途!如需商用,请到有关网站申请 10 HTTPClient http; 11 12 void setup() { 13 //在这里加入初始化相关代码,只运行一次: 14 Serial.begin(115200); 15 16 WiFi.mode(WIFI_STA); 17 WiFi.begin(ssid, passwd); 18 19 Serial.println("connecting to router... "); 20 //等待wifi连接成功 21 while (WiFi.status() != WL_CONNECTED) { 22 Serial.print("."); 23 delay(500); 24 } 25 Serial.println(""); 26 27 Serial.print("WiFi connected, local IP address:"); 28 Serial.println(WiFi.localIP()); 29 30 Serial.print("[HTTP] begin... "); 31 32 http.begin(host); //HTTP 33 34 delay(500); 35 } 36 37 void loop() { 38 if (WiFi.status() == WL_CONNECTED) 39 { 40 // start connection and send HTTP header 41 int httpCode = http.GET(); 42 if(httpCode) { 43 // HTTP header has been send and Server response header has been handled 44 Serial.printf("[HTTP] GET... code: %d ", httpCode); 45 // file found at server 46 if(httpCode == 200) { 47 String payload = http.getString(); 48 Serial.println(payload); 49 } 50 } else { 51 Serial.print("[HTTP] GET... failed, no connection or no HTTP server "); 52 } 53 } 54 55 delay(5000); 56 }
STA模式下进行HTTPServer通信

1 #include <ESP8266WiFi.h> 2 #include <ESP8266WebServer.h> 3 4 //设置您的WiFi接入信息 5 const char* ssid = "your_wifi"; 6 const char* password = "your_passwd"; 7 8 ESP8266WebServer server(80); 9 10 //自定义主页访问处理函数 11 void homepage() { 12 server.send(200, "text/plain", "test homepage !"); 13 Serial.println("用户访问了主页"); 14 } 15 16 void setup(void) { 17 //初始化串口 18 Serial.begin(115200); 19 Serial.println(""); 20 21 //初始化网络 22 WiFi.mode(WIFI_STA); 23 WiFi.begin(ssid, password); 24 while (WiFi.status() != WL_CONNECTED) { 25 delay(500); 26 Serial.print("."); 27 } 28 Serial.println(""); 29 Serial.print("IP Address: "); 30 Serial.println(WiFi.localIP()); 31 32 //初始化WebServer 33 server.on("/", homepage); 34 server.begin(); 35 Serial.println("HTTP server started"); 36 } 37 38 void loop(void) { 39 //监听客户请求并处理 40 server.handleClient(); 41 }
STA HTTPServer 点亮板载LED

#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> /*Put your SSID & Password*/ const char* ssid = "your_wifi"; // Enter SSID here const char* password = "your_passward"; //Enter Password here ESP8266WebServer server(80); uint8_t LEDpin = D9; bool LEDstatus = LOW; void setup() { Serial.begin(115200); delay(100); pinMode(LEDpin, OUTPUT); Serial.println("Connecting to "); Serial.println(ssid); //connect to your local wi-fi network WiFi.begin(ssid, password); //check wi-fi is connected to wi-fi network while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected..!"); Serial.print("Got IP: "); Serial.println(WiFi.localIP()); server.on("/", handle_OnConnect); server.on("/ledon", handle_ledon); server.on("/ledoff", handle_ledoff); server.onNotFound(handle_NotFound); server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); if(LEDstatus) digitalWrite(LEDpin, HIGH); else digitalWrite(LEDpin, LOW); } void handle_OnConnect() { LEDstatus = LOW; server.send(200, "text/html", SendHTML(false)); } void handle_ledon() { LEDstatus = HIGH; server.send(200, "text/html", SendHTML(true)); } void handle_ledoff() { LEDstatus = LOW; server.send(200, "text/html", SendHTML(false)); } void handle_NotFound(){ server.send(404, "text/plain", "Not found"); } String SendHTML(uint8_t led){ String ptr = "<!DOCTYPE html> "; ptr +="<html> "; ptr +="<head> "; ptr +="<title>LED Control</title> "; ptr +="</head> "; ptr +="<body> "; ptr +="<h1>LED</h1> "; ptr +="<p>Click to switch LED on and off.</p> "; ptr +="<form method="get"> "; if(led) ptr +="<input type="button" value="LED OFF" onclick="window.location.href='/ledoff'"> "; else ptr +="<input type="button" value="LED ON" onclick="window.location.href='/ledon'"> "; ptr +="</form> "; ptr +="</body> "; ptr +="</html> "; return ptr; }
AP HTTPServer 点亮板载LED

#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> /* Put your SSID & Password */ const char* ssid = "nodeMCU"; // Enter SSID here const char* password = "applink12345"; //Enter Password here /* Put IP Address details */ IPAddress local_ip(192,168,2,1); IPAddress gateway(192,168,2,1); IPAddress subnet(255,255,255,0); ESP8266WebServer server(80); uint8_t LEDpin = D9; bool LEDstatus = LOW; void setup() { Serial.begin(115200); pinMode(LEDpin, OUTPUT); WiFi.softAP(ssid, password); WiFi.softAPConfig(local_ip, gateway, subnet); delay(100); Serial.println(local_ip); server.on("/", handle_OnConnect); server.on("/ledon", handle_ledon); server.on("/ledoff", handle_ledoff); server.onNotFound(handle_NotFound); server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); if(LEDstatus) digitalWrite(LEDpin, HIGH); else digitalWrite(LEDpin, LOW); } void handle_OnConnect() { LEDstatus = LOW; server.send(200, "text/html", SendHTML(false)); } void handle_ledon() { LEDstatus = HIGH; server.send(200, "text/html", SendHTML(true)); } void handle_ledoff() { LEDstatus = LOW; server.send(200, "text/html", SendHTML(false)); } void handle_NotFound(){ server.send(404, "text/plain", "Not found"); } String SendHTML(uint8_t led){ String ptr = "<!DOCTYPE html> "; ptr +="<html> "; ptr +="<head> "; ptr +="<title>LED Control</title> "; ptr +="</head> "; ptr +="<body> "; ptr +="<h1>LED</h1> "; ptr +="<p>Click to switch LED on and off.</p> "; ptr +="<form method="get"> "; if(led) ptr +="<input type="button" value="LED OFF" onclick="window.location.href='/ledoff'"> "; else ptr +="<input type="button" value="LED ON" onclick="window.location.href='/ledon'"> "; ptr +="</form> "; ptr +="</body> "; ptr +="</html> "; return ptr; }

1 #include <ESP8266WiFi.h> 2 const char *ssid = "ESP8266 Website"; 3 const char *password = "12345678"; 4 WiFiServer server(80); 5 void setup() 6 { 7 Serial.begin(115200); 8 Serial.println(); 9 Serial.print("Setting soft-AP ... "); 10 11 IPAddress softLocal(192,168,1,1); 12 IPAddress softGateway(192,168,1,1); 13 IPAddress softSubnet(255,255,255,0); 14 15 WiFi.softAPConfig(softLocal, softGateway, softSubnet); 16 WiFi.softAP(ssid, password); 17 18 IPAddress myIP = WiFi.softAPIP(); 19 Serial.print("AP IP address: "); 20 Serial.println(myIP); 21 server.begin(); 22 Serial.printf("Web server started, open %s in a web browser ", WiFi.softAPIP().toString().c_str()); 23 } 24 void loop() 25 { 26 WiFiClient client = server.available(); 27 if (client) 28 { 29 Serial.println(" [Client connected]"); 30 while (client.connected()) 31 { 32 if (client.available()) 33 { 34 // String line = client.readStringUntil(13);// arduino换行符号 ascll码 13 35 String line = client.readStringUntil(' '); 36 Serial.println(line); 37 // wait for end of client's request, that is marked with an empty line 38 if (line.length() == 1 && line[0] == ' '){ 39 //返回响应内容 40 String htmlPage = String("HTTP/1.1 200 OK ") + 41 "Content-Type: text/html " + 42 "Connection: close " + // the connection will be closed after completion of the response 43 "Refresh: 5 " + // refresh the page automatically every 5 sec 44 " " + 45 "<!DOCTYPE HTML>" + 46 "<html><head><title>ESP8066 Website</title><link rel='icon' href='https://imuncle.github.io/images/avatar.jpg'><meta charset='utf-8'></head>" + 47 "<body><h1>Hello World!</h1><p>本网页由ESP8266模块展示</p><p>Designed by big_uncle</p></body>" + 48 "</html>" + 49 " "; 50 client.println(htmlPage); 51 break; 52 } 53 } 54 } 55 delay(500); 56 57 client.stop(); 58 Serial.println("[Client disonnected]"); 59 } 60 }